Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How `[]` works with lambdas

Tags:

ruby

lambda

I have this lambda (or is closure the correct usage?) and I understand the usage of .call

def multi(m)
  lambda { |n| n * m }
end

two = multi(2)
two.call(10) #=> 20  #call the proc

But I am trying to understand why/how this works?

two.(20) #=> 40 
two[20] #=> 40

I don't know whether it should or shouldn't work. Most of the time I have used square brackets with arrays.

like image 498
Bala Avatar asked Mar 22 '23 10:03

Bala


2 Answers

The documentation

prc[params,...] → obj

Invokes the block, setting the block’s parameters to the values in params using something close to method calling semantics. Generates a warning if multiple values are passed to a proc that expects just one (previously this silently converted the parameters to an array). Note that prc.() invokes prc.call() with the parameters given. It’s a syntax sugar to hide “call”.

For procs created using lambda or ->() an error is generated if the wrong number of parameters are passed to a Proc with multiple parameters. For procs created using Proc.new or Kernel.proc, extra parameters are silently discarded.

like image 125
Arup Rakshit Avatar answered Apr 06 '23 08:04

Arup Rakshit


For your first question, proc.() is a hack because Ruby doesn't let you define () on an object. It's just syntaxic sugar for proc.call().

For your second question, using square brackets on a Proc calls it.

like image 20
tckmn Avatar answered Apr 06 '23 09:04

tckmn