Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More natural way of Proc calling in Ruby 1.9

Tags:

ruby

lambda

proc

As we know, there are several way of Proc calling in Ruby 1.9

 f =->n {[:hello, n]}
 p f[:ruby]       # => [:hello, :ruby]
 p f.call(:ruby)  # => [:hello, :ruby]
 p f.(:ruby)      # => [:hello, :ruby]
 p f === :ruby    # => [:hello, :ruby]

I am curious, what is more 'natural' way of calling Proc? 'Natural', probably, means more Computer Science - like way.

like image 234
Sergey Avatar asked Oct 03 '12 11:10

Sergey


2 Answers

The second option is by far the most used.

p f.call(:ruby)  # => [:hello, :ruby]

It makes it more similar to a standard method. Also, some libraries actually rely on duck typing when validating arguments checking the availability of the #call method. In this case, using #call ensures you can provide a lambda or any other object (including a Class) that responds to #call.

Rack middlewares are a great example of this convention. The basic middleware can be a lambda, or you can supply more complex logic by using classes.

like image 181
Simone Carletti Avatar answered Sep 27 '22 20:09

Simone Carletti


I always use option 3. Considering the syntactic ambiguities of being able to call methods without parentheses, this is the closest you can get to actual method call syntax.

like image 29
Jörg W Mittag Avatar answered Sep 27 '22 21:09

Jörg W Mittag