Given a class, see if instance has method (Ruby)

user94154 picture user94154 · Jul 21, 2010 · Viewed 106k times · Source

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.

Answer

horseyguy picture horseyguy · Jul 22, 2010

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).