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

前端 未结 12 1861

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条回答
  •  没有蜡笔的小新
    2020-12-12 12:47

    While respond_to? will return true only for public methods, checking for "method definition" on a class may also pertain to private methods.

    On Ruby v2.0+ checking both public and private sets can be achieved with

    Foo.private_instance_methods.include?(:bar) || Foo.instance_methods.include?(:bar)
    

提交回复
热议问题