How do I create a reusable block/proc/lambda in Ruby?
I want to create a filter, and be able to apply it to an array or hash. For example:
def isodd(i)
i % 2 == 1
end
The I want to be able to use it like so:
x = [1,2,3,4]
puts x.select(isodd)
x.delete_if(isodd)
puts x
This seems like it should be straight forward, but I can't figure out what I need to do it get it to work.
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))
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.