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

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


当前回答

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

其他回答

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

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

present = arr.size != (arr - [e]).size
array = [ 'Cat', 'Dog', 'Bird' ]
array.include?("Dog")

在下面尝试

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

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

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

这不仅会告诉你它存在,还会告诉你它出现的次数:

 a = ['Cat', 'Dog', 'Bird']
 a.count("Dog")
 #=> 1