tags:

views:

60

answers:

2

How simplify this part of code:

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

I try sth like this, but it dosen't work proper:

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

You're looking for Array#any?

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

#each usually just returns the enumerable. #any? ors together the result of the blocks.

rampion
Thx a lot for help!
bkozal
+2  A: 

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.

Mladen Jablanović
+1 I'd +2 if I could for the additional ducktyping advice.
rampion
This checks that `a.class == Hash` or `Array`, but will fail for subclasses of them...+1 for `is_a?(Enumerable)` instead...
Marc-André Lafortune