我有一个值“狗”和一个数组[“猫”、“狗”、“鸟”]。

如何在不循环的情况下检查数组中是否存在它?是否有一种简单的方法来检查该值是否存在?


当前回答

使用Enumerable#include:

a = %w/Cat Dog Bird/

a.include? 'Dog'

或者,如果完成了大量测试,1您可以摆脱循环(甚至包括?has),并通过以下方式从O(n)变为O(1):

h = Hash[[a, a].transpose]
h['Dog']

1.我希望这是显而易见的,但为了避免反对意见:是的,对于几个查找,Hash[]和转置操作占据了配置文件的主导地位,并且每个操作本身都是O(n)。

其他回答

在下面尝试

(['Cat', 'Dog', 'Bird'] & ['Dog']).any?

如果要在MiniTest单元测试中执行此操作,可以使用assert_includes。例子:

pets = ['Cat', 'Dog', 'Bird']
assert_includes(pets, 'Dog')      # -> passes
assert_includes(pets, 'Zebra')    # -> fails 

您可以尝试:

示例:如果阵列中存在猫和狗:

(['Cat','Dog','Bird'] & ['Cat','Dog'] ).size == 2   #or replace 2 with ['Cat','Dog].size

而不是:

['Cat','Dog','Bird'].member?('Cat') and ['Cat','Dog','Bird'].include?('Dog')

注:成员?包括?都是一样的。

这可以在一条线上完成工作!

array = [ 'Cat', 'Dog', 'Bird' ]
array.include?("Dog")

Try

['Cat', 'Dog', 'Bird'].include?('Dog')