#23 Returning Procs as Values (return_proc.rb)
Let’s look at a further demonstration of how to use Procs as data generated by another function. It’s very similar to the make_incrementer.rb
script.
The Code
#!/usr/bin/env ruby
# return_proc.rb
❶ def return_proc(criterion, further_criterion=1)
proc_of_criterion = { Procs as Hash Values 'div_by?' => lambda { |i| i if (i % further_criterion).zero? }, 'is?' => lambda { |i| i == further_criterion } } # allow 'is_even' as an alias for divisible by 2 ❷ return return_proc('div_by?', 2) if criterion == ('is_even') ❸ proc_to_return = proc_of_criterion[criterion] fail "I don't understand the criterion #{criterion}" unless proc_to_return return proc_to_return end ❹ require 'boolean_golf.rb' # Demonstrate calling ...
Get Ruby by Example now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.