Ruby - 检查多个值是否出现在数组中的任何位置

时间:2022-09-25 07:53:54

I am making a text game and when you get to the final door, it is locked. You need three items (Strings in an array) to pass.

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

So I'm trying to make an if statement to see if your inventory (which can carry the three items, as well as others) contains these specific three items located anywhere.

因此,我正在尝试制作一个if语句,以查看您的库存(可以包含三个项目以及其他项目)是否包含位于任何位置的这三个特定项目。

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

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

I've tried things like using any and include, but I can't come up with a simple solution on how I would do this as my tests have shown unexpected results.

我尝试过使用any和include之类的东西,但我无法想出一个简单的解决方案,因为我的测试显示了意想不到的结果。

Thanks.

谢谢。

1 个解决方案

#1


3  

You can use array intersection:

您可以使用数组交集:

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"

or difference:

或区别:

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

#1


3  

You can use array intersection:

您可以使用数组交集:

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"

or difference:

或区别:

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