Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 347
brianegge Avatar asked Aug 28 '09 15:08

brianegge


People also ask

What is the difference between block proc and lambda in Ruby?

When using parameters prefixed with ampersands, passing a block to a method results in a proc in the method's context. Procs behave like blocks, but they can be stored in a variable. Lambdas are procs that behave like methods, meaning they enforce arity and return as methods instead of in their parent scope.

What is the main difference between procs and lambdas?

There are only two main differences. First, a lambda checks the number of arguments passed to it, while a proc does not. This means that a lambda will throw an error if you pass it the wrong number of arguments, whereas a proc will ignore unexpected arguments and assign nil to any that are missing.


1 Answers

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

isodd = lambda { |i| i % 2 == 1 } [1,2,3,4].select(&isodd) 
like image 181
Dave Ray Avatar answered Oct 16 '22 06:10

Dave Ray