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

1
  • Whatever it does is done internally to Ruby in C. It shouldn't matter. Commented Feb 24, 2013 at 7:34

1 Answer 1

15

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

Sign up to request clarification or add additional context in comments.

2 Comments

@MisterCal From the irb console, Object.class => Class .
Ah! Deleted. I made an assumption based on the fact that Object is a superclass of Class. I see now, bit confusing haha.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.