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

前端 未结 12 1855

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 certai

12条回答
  •  旧时难觅i
    2020-12-12 12:57

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

提交回复
热议问题