I know in Ruby that I can use respond_to?
to check if an object has a certain method.
But, given the class, how can I check if the instance has a certain method?
i.e, something like
Foo.new.respond_to?(:bar)
But I feel like there's gotta be a better way than instantiating a new instance.
Best Answer
I don't know why everyone is suggesting you should be using
instance_methods
andinclude?
whenmethod_defined?
does the job.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: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
:since
first_name
is both an attribute and a method (and a string of type String).