我有一个值“狗”和一个数组[“猫”、“狗”、“鸟”]。
如何在不循环的情况下检查数组中是否存在它?是否有一种简单的方法来检查该值是否存在?
我有一个值“狗”和一个数组[“猫”、“狗”、“鸟”]。
如何在不循环的情况下检查数组中是否存在它?是否有一种简单的方法来检查该值是否存在?
当前回答
这是另一种方法:使用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'].detect { |x| x == 'Dog'}
=> "Dog"
!['Cat', 'Dog', 'Bird'].detect { |x| x == 'Dog'}.nil?
=> true
您正在查找包含项?:
>> ['Cat', 'Dog', 'Bird'].include? 'Dog'
=> true
这不仅会告诉你它存在,还会告诉你它出现的次数:
a = ['Cat', 'Dog', 'Bird']
a.count("Dog")
#=> 1
如果我们不想使用include?这也适用于:
['cat','dog','horse'].select{ |x| x == 'dog' }.any?
使用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)。