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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…