我有一个值“狗”和一个数组[“猫”、“狗”、“鸟”]。
如何在不循环的情况下检查数组中是否存在它?是否有一种简单的方法来检查该值是否存在?
我有一个值“狗”和一个数组[“猫”、“狗”、“鸟”]。
如何在不循环的情况下检查数组中是否存在它?是否有一种简单的方法来检查该值是否存在?
当前回答
如果需要多次检查任何键,请将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?很好
其他回答
还有另一种方法。
假设数组是[:edit,:update,:create,:show],那么可能就是七宗致命/宁静的罪。
还有一个想法,就是从某个字符串中提取一个有效的动作:
"my brother would like me to update his profile"
然后:
[ :edit, :update, :create, :show ].select{|v| v if "my brother would like me to update his profile".downcase =~ /[,|.| |]#{v.to_s}[,|.| |]/}
您正在查找包含项?:
>> ['Cat', 'Dog', 'Bird'].include? 'Dog'
=> true
如果要在MiniTest单元测试中执行此操作,可以使用assert_includes。例子:
pets = ['Cat', 'Dog', 'Bird']
assert_includes(pets, 'Dog') # -> passes
assert_includes(pets, 'Zebra') # -> fails
如果我们不想使用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)。