我有一个值“狗”和一个数组[“猫”、“狗”、“鸟”]。
如何在不循环的情况下检查数组中是否存在它?是否有一种简单的方法来检查该值是否存在?
我有一个值“狗”和一个数组[“猫”、“狗”、“鸟”]。
如何在不循环的情况下检查数组中是否存在它?是否有一种简单的方法来检查该值是否存在?
当前回答
如果需要多次检查任何键,请将arr转换为哈希,然后检查O(1)
arr = ['Cat', 'Dog', 'Bird']
hash = arr.map {|x| [x,true]}.to_h
=> {"Cat"=>true, "Dog"=>true, "Bird"=>true}
hash["Dog"]
=> true
hash["Insect"]
=> false
Hash#has_key的性能?与Array#include相比?
Parameter Hash#has_key? Array#include Time Complexity O(1) operation O(n) operation Access Type Accesses Hash[key] if it Iterates through each element returns any value then of the array till it true is returned to the finds the value in Array Hash#has_key? call call
对于一次性检查,使用include?很好
其他回答
检查是否存在
使用include?
例子:
arr = [1, 2, 3]
arr.include?(1) -> true
arr.include?(4) -> false
支票不存在
使用排除?
例子:
arr = %w(vietnam china japan)
arr.exclude?('usa') -> true
arr.exclude?('china') -> false
这是另一种方法:使用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
有趣的事实,
可以使用*检查case表达式中的数组成员资格。
case element
when *array
...
else
...
end
注意when子句中的小*,它检查数组中的成员身份。
splat运算符的所有常见魔术行为都适用,所以例如,如果数组实际上不是一个数组,而是一个元素,那么它将匹配该元素。
如果我们不想使用include?这也适用于:
['cat','dog','horse'].select{ |x| x == 'dog' }.any?