Home > database >  Unable to call ruby lambda
Unable to call ruby lambda

Time:09-05

I'm having issue in calling ruby lambda as below.

I'm having a function which accepts a Proc. And lambda definition as below.

def call_proc_with_arg(&b)
   b.call(1)
end

lam = -> (a) { puts "printing the argument #{a}"}

And when I try to pass the lambda to function as,

call_proc_with_arg(lam)

I'm getting the error,

Traceback (most recent call last): 6: from /usr/bin/irb:23:in <main>' 5: from /usr/bin/irb:23:in load' 4: from /Library/Ruby/Gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in <top (required)>' 3: from (irb):118 2: from (irb):118:in rescue in irb_binding' 1: from (irb):52:in `call_block' ArgumentError (wrong number of arguments (given 1, expected 0))

Whereas the function works with block,

call_proc_with_arg {|a| puts "printing the argument #{a}"}

What am I missing with lambda?

CodePudding user response:

You need to use the following syntax to call the method passing the block, as you defined b as block in the method signature:

call_proc_with_arg(&lam)

The only way you could use call_proc_with_arg(lam) is if you treat the argument not as a method block, but as a first-class argument:

def call_proc_with_arg(b)
   b.call(1)
end

call_proc_with_arg(lam)

Each syntax has its own advantage/disadvantage, and it depends on the use case. If you want to leverage blocks, then the first one is the most common one. In such case, you can also use a more common yield syntax:

def call_proc_with_arg(&b)
   yield 1
end

instead of referencing the block b variable directly.

The second one would be necessary if you want to pass more than one lambda as parameter, as a single method cannot take multiple blocks.

CodePudding user response:

You can call it different ways

lam = -> (a) { puts "printing the argument #{a}"}
# method with parameter as lambda
def call_proc_with_arg(b)
  b.call(1)
end

call_proc_with_arg(lam)
# method without parameters
def call_proc_with_arg
  yield 1
end

call_proc_with_arg(&lam)
# method without parameters with named block
def call_proc_with_arg(&b)
  b.call(1)
end

call_proc_with_arg(&lam)
  • Related