I came across this code while trying to learn about creating your own method_missing method, and I don't understand it. What I don't understand are these parts: method_sym[-1] == "=" and method_sym[0..-2] What do they refer to? I tried some simulations in irb, but this just returned some weird stuff.
Could anyone break it down for me? I would really appreciate it. Thanks!
class UberHash
def method_missing(method_sym, *args, &block)
if method_sym[-1] == "="
instance_variable_set("@#{method_sym[0..-2]}", args[0])
else
instance_variable_get("@#{method_sym}")
end
end
end
method_sym, i.e. the first argument ofmethod_missingis theSymbolinstance representing the name of the method. So, for example, if you calland Ruby fails to find
foomethod,a.method_missing(:foo)will be called.Next,
Symbol#[]method is used to return nth character of the symbol or some characters range if you passRangeinto it.-1passed into this method represent "last character".-2represents 'the character before the last one' etc. So:argsrepresents all the arguments passed into missing method. So, if you call your method with:argsinmissing_methodwill be:Methods in Ruby can be named with
=at the end , that's how you create setter methods, like:It's regular method and
A.new.foo = some_valueis only a syntactic sugar, under the hood, it's equivalent toA.new.foo=(some_value). So if you calland the
b.foo=is not defined, Ruby is going to call:thus the
=asmethod_sym[-1].