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