Why does Ruby require .call to call Proc?

I just wondered if there was a good reason or even an advantage in calling Proc using proc.call(args) in Ruby, which makes the higher order syntax much more verbose and less intuitive.

Why not just proc(args) ? Why distinguish between functions, lambdas and blocks? Basically, it's all the same, why is this confusing syntax? Or is there some point for this, I donโ€™t understand?

+6
syntax ruby
source share
3 answers

You need some way to distinguish a Proc call from transmitting it.

In Python and ECMAScript, this is simple: with parentheses this is a call, without it there is none. In Ruby, parenthesis exclusion is also a call, so there must be some other way of distinguishing it.

In Ruby 1.8, Proc#call and its alias Proc#[] serve this distinction. Starting with Ruby 1.9, obj.(arg) is the syntax sugar for obj.call(arg) and Proc#() also an alias for Proc#call .

So you can call Proc as follows:

  • foo.call (1, 2, 3)
  • foo [1, 2, 3]
  • phew. (1, 2, 3)

And you can even define () for your own classes.

By the way, the same problem is why you should use a method method to get a method object.

+11
source share

In ruby, you can have a local variable and method, both of which are called foo. Assuming the method is private, the only way to call it is foo(args) ( self.foo(args) will not work for private methods that cannot have an explicit receiver). If ruby โ€‹โ€‹allows the operator () to be overloaded so that foo in foo(bar) can be a variable, there would be no way to call the private method foo when there is also a local variable called foo.

Note that with functions such as define_method and method_missing , it is not always possible to avoid situations where you have methods and local variables with the same name.

+6
source share

You want to be able to pass it on without naming it, right? The requirement that it be explicitly called allows this. Otherwise, every time you try to use proc as a parameter, you end up calling it.

+2
source share

All Articles