I am trying to understand Ruby and it's not clear for me, how Ruby converts name of method into a Symbol?
In method definition we give it a name meth
module Mod
def meth
puts 'm'
end
end
But if we want to check if a method exists, we pass the symbol :meth as a parameter to method_defined
Mod.method_defined?(:meth)
=> true
Please, help me understand, how does this work?
This is due to ruby's method invocation syntax: You can call a method just by referencing its name, without any further syntax like brackets () needed.
Now, if the method_defined? method would take the method itself as an argument, there would be no way to do so without actually invoking the method and thereby producing an error if the method would not exist:
Mod.method_defined?(meth)
#=> NameError: undefined local variable or method `meth'
With symbols, there is no invocation taking place, it is just normally instantiated and not producing any error. Behind the curtains, method_defined? can then lookup if a method exists by the name the symbol references without producing any error.
it's not clear for me, how Ruby converts name of method into :symbol?
That's the way Method#name works, it returns the name of the method as a symbol:
m = "foo".method(:size) #=> #<Method: String#size>
m.name #=> :size
m.call #=> 3
All methods referencing other methods usually work this way. For example, Object#methods returns a array of method names:
"foo".methods
#=> [:<=>, :==, :===, :eql?, :hash, :casecmp, :+, :*, ...]
In method definition we give it name
meth... but if we want check, does any method exist, we give intomethod_definedsymbol:meth
meth would be a reference to a variable or another method, whereas :meth is just a symbol:
meth = :foo
Mod.method_defined? meth #=> false, equivalent to Mod.method_defined? :foo
Mod.method_defined? :meth #=> true
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