2

One can do this:

s="puts"
send(s,"Hello World!")
# => Hello World!

How can one check if s is a method? If it was:

s="nomethod"

send(s,arg) will fail.

This would be cool:

ismethod? s

P.S. I am porting something from PHP, which relies on:

if (function_exists($s)) 
    ...

If only Ruby had something so simple.

1 Answer 1

6

Try this:

respond_to?(method_name)

It should return true if the current object (self) responds to a method by that name. You can use respond_to? on any Ruby object.

http://ruby-doc.org/core/Object.html#method-i-respond_to-3F

Sign up to request clarification or add additional context in comments.

5 Comments

respond_to?(s) results in false, as does (obviously) resond_to?("puts"). What's odd is that respond_to?(puts) results in TypeError: nil is not a symbol nor a string (respond_to?(gak) results in NameError: undefined local variable or method 'gak' which is expected)
oh, and thank you for your input, it's leading me in the right direction
(p.s. the TypeError above is probably because puts returns nil.)
Yeah, respond_to?('puts') is actually retuning nil for me in IRB, and I don't know why. But Kernel.respond_to?('puts') returns true.
Yes, I think that is the answer. I did not know about Kernel module. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.