tags:

views:

306

answers:

3

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.

+9  A: 

Create a lambda and then convert to a block with the & operator:

isodd = lambda { |i| i % 2 == 1 }
[1,2,3,4].select(&isodd)
Dave Ray
+6  A: 

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.

Daniel Vandersluis
+3  A: 
puts x.select(&method(:isodd))
Antti Tarvainen
Dave's and Daniel's answers are also good. This is an alternative.
Antti Tarvainen