Ruby - 检查数组中是否出现多个值

时间:2014-12-11 06:09:18

标签: ruby arrays

我正在制作一个文字游戏,当你到达最后一扇门时,它被锁定了。你需要传递三个项目(数组中的字符串)。

所以我试图制作一个if语句来查看你的库存(可以带有三个项目,以及其他项目)是否包含位于任何地方的这三个特定项目。

array1 = ["key1", "key2", "key3", "sword", "dagger"]
array2 = ["key1", "key2", "key3"]

if array1.include? array2
  puts "it does"
else
  puts "it doesn't"
end

我尝试过使用any和include之类的东西,但是由于我的测试显示出意想不到的结果,我无法想出如何做到这一点的简单解决方案。

感谢。

1 个答案:

答案 0 :(得分:3)

您可以使用数组交集:

array1 = ["key1", "key2", "key3", "sword", "dagger"]
array2 = ["key1", "key2", "key3"]

puts (array1 & array2 == array2) ? "it does" : "it doesn't"
  #=> "it does"

array2 = ["key1", "key2", "cat"]
puts (array1 & array2 == array2) ? "it does" : "it doesn't"
  #=> "it doesn't"

或差异:

puts (array2 - array1).empty? ? "it does" : "it doesn't"