I am confused when using each of these methods. From the documentation respond_to?:
Returns true if obj matches this method. Private methods are included in the search only if the optional second parameter is true.
If the method is not implemented, like Process.fork on Windows, File.lchmod on GNU / Linux, etc. It returns false.
If the method is not defined, answer_to_missing? the method is called and the result is returned.
And respond_to_missing?:
Hook method to return whether obj can respond to the id method or not.
See #respond_to ?.
Both methods take 2 arguments.
Both methods seem the same (check if any object responds to this method), so why should we use (have) both?
"resond_to_missing?" :
class A
def method_missing name, *args, &block
if name == :meth1
puts 'YES!'
else
raise NoMethodError
end
end
def respond_to_missing? name, flag = true
if name == :meth1
true
else
false
end
end
end
[65] pry(main)> A.new.method :meth1
respond_to? ?
:
respond_to? , :
respond_to_missing? , :
:
def method_missing name, *args, &block
arr = [:a, :b, :c]
if arr.include? name
puts name
else
raise NoMethodError
end
end
:
class A
def initialize name
@str = String name
end
def method_missing name, *args, &block
@str.send name, *args, &block
end
end
2. , .
/ ( ):
1.9.3 ( ), respond_to_missing?, respond_to?
:
? - ? , / , .