Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Ruby symbol as method call [duplicate]

Tags:

ruby

ruby-1.9

class A
   def test
       "Test from instance"
   end
   class << self
       def test
           "Test from class"
       end
    end
end

p A.send(:test)    # "Test from class"
p A.new.method(:test).call  # "Test from instance"

Here symbol works as expected, but here:

s="test"
s1=:s
p s1   # :s

why :s is printed here?? I dont understand the reason behind it. Can anyone please explain for me ?

like image 551
sunny1304 Avatar asked Feb 06 '13 18:02

sunny1304


Video Answer


1 Answers

Symbols are just a special kind of stringlike value that's more efficient for the runtime to deal with than a regular string. That's it. They aren't methods or variables or anything like that.

When you do A.send(:test), all you are doing is saying "hey, A, call the method named 'test'". You aren't sending the method itself, just the name; it's the logic inside send that is responsible for looking up the actual method to call.

The same thing goes when you ask for method with A.new.method(:test). All you are passing to method is the name "test", not the method defined with that name. It's up to method to use the name and find the actual method so it can return it, and it's that return value - a Method object - that you are doing call on. You can't do call on a Symbol like :test, because it's just a name.

like image 115
Mark Reed Avatar answered Sep 19 '22 05:09

Mark Reed