简化多个is_a?调用对象

时间:2021-10-08 11:46:26

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 }

2 个解决方案

#1


9  

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.

我想你应该解释一下你需要达到的目标。也许您需要检查的唯一事情是您的对象是否是Enumerable,或者即使它是respond_to?一些特殊的方法。

#2


5  

You're looking for Array#any?

您正在寻找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.

#each通常只返回可枚举的。 #任何?或者块的结果。

#1


9  

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.

我想你应该解释一下你需要达到的目标。也许您需要检查的唯一事情是您的对象是否是Enumerable,或者即使它是respond_to?一些特殊的方法。

#2


5  

You're looking for Array#any?

您正在寻找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.

#each通常只返回可枚举的。 #任何?或者块的结果。