It means that from the outside of Object#respond_to?, “not defined” and
“not implemented” look the same.
From the inside, it differentiates between the two because a method
could be “defined” in Ruby, but not “implemented” on the current
platform.
There are specific exceptions if you need to specify the difference,
although for the purposes of most users, you shouldn’t need to go into
that level of detail.
Ok… Let me tell you why I asked this question and why the documentation
a bit unclear to me.
Suppose I called “hello”.respond_to?(:foo),then I am quite sure I would
get false back. Now my question is - Is respond_to_missing? method
is being called or not,in this scenario ?
Suppose I called “hello”.respond_to?(:foo),then I am quite sure I would
get false back. Now my question is - Is respond_to_missing? method
is being called or not,in this scenario ?
What’s not clear about this?
“If the method is not defined, respond_to_missing? method is called”
Yes, as far as I can see from the C code, all that the
respond_to_missing? method does is return false. The real work is done
inside respond_to? and the methods it calls.
Suppose I called “hello”.respond_to?(:foo),then I am quite sure I would
get false back. Now my question is - Is respond_to_missing? method
is being called or not,in this scenario ?
What’s not clear about this?
“If the method is not defined, respond_to_missing? method is called”
Yes there is a point of doubt. So you mean the false is returned by respond_to_missing? method in my example. Right?
class Foo
def method_missing(meth)
“#{meth} not found”
end
end
foo = Foo.new
foo.bar
=> “bar not found”
foo.method(:bar)
~> -:8:in method': undefined methodbar’ for class `Foo’ (NameError)
~> from -:8:in `’
Now to handle this error I think I need to override the method #respond_to_missing? .
class Foo
def respond_to_missing?(meth,include_private = false)
p “checking if I am being called or not”
end
def baz
“I do exist”
end
def method_missing(meth)
“#{meth} not found”
end
end
foo = Foo.new
foo.bar
=> “bar not found”
foo.method(:bar)
>> “checking if I am being called or not”
conclusions :-
From this examples I can think of 2 situations,where I should override
the method #method_missing and respond_to_missing?.
Any other cases do you guys wanted me to point,when I must need to think
of method_missing or respond_to_missing? to override ? Obviously
overriding both of them cool way to handle any errors.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.