sunny1304
sunny1304

Reputation: 1694

Understanding the Ruby method #call

def test
  "Hello World"
end

p method(:test).call  #"Hello World"
p method("test").call #"Hello World"

My question is: what happens when we pass a symbol to the call method? Will ruby convert the symbol to a String and then execute it? If so, then what is it's purpose?

And if not, then what actually happens? Can you please elaborate? Sorry if I fail to make myself clear.

Upvotes: 17

Views: 11849

Answers (1)

Steve Jorgensen
Steve Jorgensen

Reputation: 12341

When you execute def test ... outside of any explicit class or module definition, you are essentially in the Object class context, so test is now an instance method of Object

In irb ...

1.8.7 :001 > def test
1.8.7 :002?>   "Hello world"
1.8.7 :003?>   end
 => nil
1.8.7 :004 > Object.instance_methods.sort
 => ["==", "===", "=~", "__id__", "__send__", "class", "clone", "display", "dup", "enum_for", "eql?", "equal?", "extend", "freeze", "frozen?", "hash", "id", "inspect", "instance_eval", "instance_exec", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "is_a?", "kind_of?", "method", "methods", "nil?", "object_id", "private_methods", "protected_methods", "public_methods", "respond_to?", "send", "singleton_methods", "taint", "tainted?", "tap", "test", "to_a", "to_enum", "to_s", "type", "untaint"]

method is an instance method of the Object class which is inherited by essentially everything. When you call method outside of any explicit class or module definition, you are essentially invoking it as a method of the Object class, and that class is itself an instance of Class, which is a subclass of Object (sorry -- I know that's a bit confusing to follow).

So -- the method method takes a string or a symbol and returns an object encapsulating the bound method of that name on the same object that .method was called on. In this case, that's the test method bound to the Object object.

method(:test).call means call the test method of Object which is what you defined previously via def test ....

Upvotes: 15

Related Questions