How do I create a reusable block/proc/lambda in Ruby?
You can create a named Proc
and pass it to the methods that take blocks:
isodd = Proc.new { |i| i % 2 == 1 }
x = [1,2,3,4]
x.select(&isodd) # returns [1,3]
The &
operator converts between a Proc
/lambda
and a block, which is what methods like select
expect.
Create a lambda and then convert to a block with the &
operator:
isodd = lambda { |i| i % 2 == 1 }
[1,2,3,4].select(&isodd)
puts x.select(&method(:isodd))