[26] pry(main)> [1,2,3,4].any?{|x| [2,5].include?(x)}
=> true
[27] pry(main)> [1,2,3,4].include?(2,5)
ArgumentError: wrong number of arguments(2 for 1)
from (pry):27:in `include?'
[29] pry(main)> [1,2,3,4].include?(2 || 5) # I want this behavior...
=> true
[30] pry(main)> [1,2,3,4].include?(5 || 2) # but that only works because the above expression evaluates to 2... this to 5
=> false
是否有某种快捷方式可以查看数组中是否包含任何内容? .include
允许我针对单个值测试数组...我似乎无法想出一种聪明的方法来检查多个,而不是我顶部的原始.any?
。
答案 0 :(得分:3)
您可以计算交点并查看结果数组中是否有任何
2.1.1 :013 > ([1,2,3,4] & [1,2]).any?
=> true
2.1.1 :014 > ([1,2,3,4] & [5,6]).any?
=> false
2.1.1 :015 > ([1,2,3,4] & [1,6]).any?
=> true
请参阅:http://www.ruby-doc.org/core-2.1.1/Array.html#method-i-26
答案 1 :(得分:1)
a = [1,2,3,4]
b = [2,5]
(a & b) == b #=> false, will check if all items of b are contained in a
(a & b).any? #=> true, will check if any item of b is contained in a
PS:2 || 5
等于2
,5 || 2
与5
相同。