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

#21 Using Procs for Filtering (matching_members.rb)

So far, we’ve seen that to create a Proc, we call lambda with a block describing what that Proc should do. This would lead you to believe that there is a special relationship between Procs and blocks, which there is. Our next script demonstrates how to use Procs in place of blocks.

The Code

  #!/usr/bin/env ruby
  # matching_members.rb

  =begin rdoc
  Extend the built-in <b>Array</b> class.
  =end
  class Array

  =begin rdoc
  Takes a <b>Proc</b> as an argument, and returns all members
  matching the criteria defined by that <b>Proc</b>.
  =end
❶   def matching_members(some_proc)    Procs as Arguments find_all { |i| some_proc.call(i) } end end ❷ digits = (0..9).to_a lambdas = Hash.new() lambdas['five+'] = lambda { |i| ...

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