Xullnn
Xullnn

Reputation: 405

How the '.call' method be triggered by a returning integer in Ruby?

I encountered a code kata, it asks to implement a add(n) method which can chain multiple numbers then add them up, like:

add(1).(2).(3).(4).(5);  # => 15

When I first started,I thought it might involve method_missing method, so I firstly made a simplified version to see how the *args were handled when I was chaining a .(n) after a method which would return a integer, I chose rand to do this.

def method_missing(m, *args)
  p m
  p args
end

> rand(10).(9).(8)
# some other methods add empty array
:call
[9]
:call
[8]
 => [8]

Then I found the following chained .(n) just call .call method and take n as its parameter. Based on another similar question I just rewrite the call method in class Integer:

class Integer
  def call(x)
    self + x
  end
end


def add(n)
  n
end

Then I get the result.

The question is I knew that the .call method is usually sent to a Proc object. But here the add(n) (as well as rand and other methods returning an integer) just simply returns a integer.

Why this can trigger call method? Did I miss something?

Upvotes: 1

Views: 285

Answers (1)

iCodeSometime
iCodeSometime

Reputation: 1643

.() is just a shortcut for .call() Yes, the call method is usually used to run proc objects, but that doesn't make it anything special, just a regular method that a proc object has implemented. If you define it to do something else, the shortcut still works as normal

Upvotes: 3

Related Questions