I’m very new to Ruby and now trying to understand something about metaprogramming.
I want to return missed method name:
class Numeric
attr_accessor :method_name
def method_missing(method_id)
method_name = method_id.to_s
self
end
def name
method_name
end
end
10.new_method.name #this should return new_method, but returns nil
Inside your
method_missing,method_nameis being interpreted as a local variable rather than themethod_missing=mutator method that you’re expected. If you explicitly add the receiver then you’ll get what you want:Alternatively, you could assign to the
@method_nameinstance variable:The
attr_accessormacro just adds two methods for you soattr_accessor :pis shorthand for this:You’re free to use the underlying instance variable when you want or need to.