ruby

Simplify multiple is_a? calls on object


How to rewrite this line using an iterator?

actor.inspect if actor.is_a? Array || actor.is_a? Hash

My attempt that dosen't work:

actor.inspect if [Array, Hash].each { |c| actor.is_a? c }

Solution

  • If you want to match exact classes (and not descendants), you can use:

    [Hash, Array].member? a.class
    

    I think you should explain what exactly you need to achieve. Perhaps the only thing you need to check is if your object is an Enumerable or not, or even if it respond_to? some particular method.