I have a function in my .irbrc which basically builds together a string form certain input parameters, and then is supposed to check, whether another function with name of this string exists. I'm doing it like this
methodname = ... # Calculate a string
if respond_to?(methodname)
....
end
This does not work in that respond_to? returns false even in those cases where in my opinion it should return true. I have boiled down the problem to the following simple case:
I have in my .irbrc
def foo
end
def respond_to_foo?
respond_to?(:foo)
end
puts "Respond: #{respond_to_foo?}"
Running irb
, this outputs false. I would expect it to print true instead. Still, I am able to run foo
from within irb.
I guess that this has to do with the scope in which irb defines my methods. For instance, self.foo
does not work (private method 'foo' called for main:Object), while send.foo
does work (since it bypasses privacy). This looks like a clue to my problem, but I still can't come up with an explanation, nor find the proper way for doing my task.
Could someone enlighten me?
To answer my own question: It just occured to me, that I could use
private_methods.include?(:foo)
This does work, but it looks a bit like a hack to me. If someone knows a better way, please let me know.