How do I create a reusable block/proc/lambda in Ruby?

Viewed 24694

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.

4 Answers

If you are using this in an instance, and you do not require any other variables outside of the scope of the proc (other variables in the method you're using the proc in), you can make this a frozen constant like so:

ISODD = -> (i) { i % 2 == 1 }.freeze
x = [1,2,3,4]
x.select(&ISODD)

Creating a proc in Ruby is a heavy operation (even with the latest improvements), and doing this helps mitigate that in some cases.

Related