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

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


当前回答

这是另一种方法:使用Array#索引方法。

它返回数组中元素第一次出现的索引。

例如:

a = ['cat','dog','horse']
if a.index('dog')
    puts "dog exists in the array"
end

index()也可以采用一个块:

例如:

a = ['cat','dog','horse']
puts a.index {|x| x.match /o/}

这将返回数组中包含字母“o”的第一个单词的索引。

其他回答

这是另一种方法:使用Array#索引方法。

它返回数组中元素第一次出现的索引。

例如:

a = ['cat','dog','horse']
if a.index('dog')
    puts "dog exists in the array"
end

index()也可以采用一个块:

例如:

a = ['cat','dog','horse']
puts a.index {|x| x.match /o/}

这将返回数组中包含字母“o”的第一个单词的索引。

您正在查找包含项?:

>> ['Cat', 'Dog', 'Bird'].include? 'Dog'
=> true

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

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

如果你不想使用include?您可以首先将元素包装在数组中,然后检查包装的元素是否等于数组和包装的元素的交集。这将返回一个基于相等的布尔值。

def in_array?(array, item)
    item = [item] unless item.is_a?(Array)
    item == array & item
end

Try

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