我正在研究 Rails 的 ActiveSupport 扩展,并且遇到了“in?”方法。对我来说,它的外观和工作方式与“包含?”完全相同。方法,只不过是反过来而已。
([1..5]).include? 1
1.in? ([1..5])
我一直在使用“包含?”自从我第一次开始使用 Rails 以来,我一直在使用 Rails 方法,所以有趣的是还有另一种方法可以完成完全相同的事情。我缺少的两种方法有什么区别吗?
EDIT
有没有使用“in”的场景?会比使用“包含?”受益更多?因为现在我所能想到的就是“在?”给出“包含?”是一个毫无意义的方法已经为其目的而存在。
在?该方法在 Rails 3.1 之后可用。那么如果你想用在?方法中,我们需要标记 require '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
从 Rails 控制台:
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)
你可以看到,包括?比在更快?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)