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

前端 未结 12 1832

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:44

    If you're checking to see if an object can respond to a series of methods, you could do something like:

    methods = [:valid?, :chase, :test]
    
    def has_methods?(something, methods)
      methods & something.methods == methods
    end
    

    the methods & something.methods will join the two arrays on their common/matching elements. something.methods includes all of the methods you're checking for, it'll equal methods. For example:

    [1,2] & [1,2,3,4,5]
    ==> [1,2]
    

    so

    [1,2] & [1,2,3,4,5] == [1,2]
    ==> true
    

    In this situation, you'd want to use symbols, because when you call .methods, it returns an array of symbols and if you used ["my", "methods"], it'd return false.

提交回复
热议问题