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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With