Given a class, see if instance has method (Ruby)
I don't know why everyone is suggesting you should be using instance_methods
and include?
when method_defined?
does the job.
class Test
def hello; end
end
Test.method_defined? :hello #=> true
NOTE
In case you are coming to Ruby from another OO language OR you think that method_defined
means ONLY methods that you defined explicitly with:
def my_method
end
then read this:
In Ruby, a property (attribute) on your model is basically a method also. So method_defined?
will also return true for properties, not just methods.
For example:
Given an instance of a class that has a String attribute first_name
:
<instance>.first_name.class #=> String
<instance>.class.method_defined?(:first_name) #=> true
since first_name
is both an attribute and a method (and a string of type String).
You can use method_defined?
as follows:
String.method_defined? :upcase # => true
Much easier, portable and efficient than the instance_methods.include?
everyone else seems to be suggesting.
Keep in mind that you won't know if a class responds dynamically to some calls with method_missing
, for example by redefining respond_to?
, or since Ruby 1.9.2 by defining respond_to_missing?
.