How to create a reusable / proc / lambda block in Ruby?

I want to create a filter and apply it to an array or hash. For example:

def isodd(i) i % 2 == 1 end 

I want to be able to use it like this:

 x = [1,2,3,4] puts x.select(isodd) x.delete_if(isodd) puts x 

It seems like it should be straightforward, but I can't figure out what I need to do to get it to work.

+49
ruby
Aug 28 '09 at 15:01
source share
4 answers

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

 isodd = lambda { |i| i % 2 == 1 } [1,2,3,4].select(&isodd) 
+73
Aug 28 '09 at 15:09
source share
 puts x.select(&method(:isodd)) 
+31
Aug 28 '09 at 15:17
source share

You can create a named Proc and pass it to methods that accept 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, as expected by select .

+20
Aug 28 '09 at 15:10
source share

If you use this in an instance and you do not need any other variables outside the scope of the proc (other variables in the method in which you use proc), you can make this a frozen constant like this:

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

Creating a procedure in Ruby is a complex operation (even with the latest improvements), and in some cases it helps mitigate this.

0
May 08 '19 at 23:43
source share



All Articles