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

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


当前回答

['Cat', 'Dog', 'Bird'].detect { |x| x == 'Dog'}
=> "Dog"
!['Cat', 'Dog', 'Bird'].detect { |x| x == 'Dog'}.nil?
=> true

其他回答

在任何数组中查找元素有多种方法,但最简单的方法是“in?”方法

example:
arr = [1,2,3,4]
number = 1
puts "yes #{number} is present in arr" if number.in? arr

您正在查找包含项?:

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

如果我们不想使用include?这也适用于:

['cat','dog','horse'].select{ |x| x == 'dog' }.any?

还有一种方法可以做到这一点:

arr = ['Cat', 'Dog', 'Bird']
e = 'Dog'

present = arr.size != (arr - [e]).size

有趣的事实,

可以使用*检查case表达式中的数组成员资格。

case element
when *array 
  ...
else
  ...
end

注意when子句中的小*,它检查数组中的成员身份。

splat运算符的所有常见魔术行为都适用,所以例如,如果数组实际上不是一个数组,而是一个元素,那么它将匹配该元素。