Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Ruby call the `call` method when I don't supply the method name?

Tags:

ruby

Given the following module:

module Foo
  def self.call
    'foo'
  end
end

I would of course expect the following to work:

puts Foo.call  # outputs "foo"

However, I did not expect this to work:

puts Foo.()    # outputs "foo"

Apparently when the method name is left off, Ruby assumes that I want to call the call method. Where is this documented, and why does it behave that way?

like image 934
Matt Huggins Avatar asked Oct 04 '13 19:10

Matt Huggins


1 Answers

Proc#call:

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”.

I did some research and found method #() is a syntactic sugar of the method #call..Look at the error as below :

module Foo
  def self.bar
    12
  end
end
Foo.()
#undefined method `call' for Foo:Module (NoMethodError)

As OP defined the #call method in module Foo class,Foo#call is called in an attempt of Foo.().

Here is some more examples :

"ab".method(:size).() # => 2
"ab".method(:size).call # => 2
"ab".() # undefined method `call' for "ab":String (NoMethodError)

See here what Matz said So compromise with object.() syntax introduced in 1.9...

like image 189
Arup Rakshit Avatar answered Oct 12 '22 13:10

Arup Rakshit