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

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


当前回答

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

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

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

其他回答

在下面尝试

(['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

如果需要多次检查任何键,请将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?很好

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

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

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

有一个入口?正如@campeterson所指出的,ActiveSupport(Rails的一部分)中的方法。因此,在Rails中,或者如果您需要“active_support”,您可以编写:

'Unicorn'.in?(['Cat', 'Dog', 'Bird']) # => false

OTOH,没有in运算符或#in?尽管Ruby内核的顶级成员Yusuke Endoh之前就提出过这种方法,但这种方法在Ruby本身也是如此。

正如其他人所指出的,相反的方法包括?存在,对于所有枚举,包括Array、Hash、Set、Range:

['Cat', 'Dog', 'Bird'].include?('Unicorn') # => false

请注意,如果数组中有许多值,则将逐个检查这些值(即O(n)),而查找哈希值的时间将是恒定的(例如O(1))。例如,如果数组是常量,最好使用Set。例如:

require 'set'
ALLOWED_METHODS = Set[:to_s, :to_i, :upcase, :downcase
                       # etc
                     ]

def foo(what)
  raise "Not allowed" unless ALLOWED_METHODS.include?(what.to_sym)
  bar.send(what)
end

快速测试显示,呼叫包括?在10个元素上调用Set比在等效数组上调用Set快3.5倍(如果找不到元素)。

最后一点:使用include时要小心?在Range上,有一些微妙之处,所以请参考文档并与封面进行比较?。。。