O'Reilly logo

Ruby by Example by Kevin C. Baird

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

#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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required