Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a lambda as a block

Tags:

ruby

lambda

I'm trying to define a block that I'll use to pass the the each method of multiple ranges. Rather than redefining the block on each range, I'd like to create a lamba, and pass the lambda as such:

count = 0 procedure = lambda {|v| map[count+=1]=v} ("A".."K").each procedure ("M".."N").each procedure ("P".."Z").each procedure 

However, I get the following error:

 ArgumentError: wrong number of arguments(1 for 0)     from code.rb:23:in `each' 

Any ideas what's going on here?

like image 804
heneryville Avatar asked Nov 17 '11 04:11

heneryville


People also ask

What is the difference between a lambda a block and a proc?

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.

How is a block different from a proc?

Procs are objects, blocks are notA proc (notice the lowercase p) is an instance of the Proc class. This lets us call methods on it and assign it to variables. Procs can also return themselves. In contrast, a block is just part of the syntax of a method call.

What is the main difference between procs and lambdas?

In Ruby, a lambda is an object similar to a proc. Unlike a proc, a lambda requires a specific number of arguments passed to it, and it return s to its calling method rather than returning immediately. proc_demo = Proc.

How do you call a lambda function in Ruby?

With Ruby, the lambda keyword is used to create a lambda function. It requires a block and can define zero or more parameters. You call the resulting lambda function by using the call method. The literal operator is succinct and commonly used.


1 Answers

Tack an ampersand (&) onto the argument, for example:

("A".."K").each &procedure 

This signifies that you're passing it as the special block parameter of the method. Otherwise it's interpreted as a normal argument.

It also mirrors they way you'd capture and access the block parameter inside the method itself:

# the & here signifies that the special block parameter should be captured # into the variable `procedure` def some_func(foo, bar, &procedure)   procedure.call(foo, bar) end  some_func(2, 3) {|a, b| a * b } => 6 
like image 100
numbers1311407 Avatar answered Sep 30 '22 18:09

numbers1311407