导轨:导轨中'in?'和'include?'之间的差异



我正在浏览Rails的ActiveSupport扩展,我遇到了'in?'方法。对我来说,它的外观和工作方式与"include?"方法完全相同,但恰恰相反。

([1..5]).include? 1
1.in? ([1..5])

自从我第一次开始使用 Rails 以来,我一直在使用"include?"方法,所以有趣的是,还有另一种方法可以做同样的事情。我缺少的两种方法有什么区别吗?

编辑

有没有使用"in?"比使用"include"更有益的情况?因为现在,我所能想到的就是"in?"是一个相当毫无意义的方法,因为"include?"已经存在了。

in? 方法在 Rails 3.1 之后可用。 所以如果你想使用吗?方法,我们需要标记需要"active_support"然后我们可以利用 in?方法。

但是包含方法可用于所有枚举对象。就像在普通的 ruby 控制台中一样,您可以尝试:

From irb: 
(1..5).include? 1 #you are checking for include? on a range.
=> true
(1..5).to_a.include? 1 # you are checking on an Array.
=> true 
2.1.5 :023 > 1.in?(1..5)
NoMethodError: undefined method `in?' for 1:Fixnum

从轨道控制台:

1.in?(1..5)
=> true 
(1..5).include? 1
=> true

检查他们的表现:

 require 'benchmark'
=> false
 puts Benchmark.measure { 90000.in?(1..99000)}
  0.000000   0.000000   0.000000 (0.000014)
 puts Benchmark.measure { (1..99000).include? 90000 }
  0.000000   0.000000   0.000000 ( 0.000007)

你可以看到,包括?比在?

最新更新