问题描述
我在浏览 Rails 的 ActiveSupport 扩展时遇到了in?"方法.对我来说,它的外观和工作方式与包含?"完全一样.方法,但正好相反.
I was going over Rails' ActiveSupport extensions and I came across the 'in?' method. To me, it looks and works exactly like the 'include?' method, but just in reverse.
([1..5]).include? 1
1.in? ([1..5])
我一直在使用包含?"方法自从我第一次开始使用 Rails 以来,所以有趣的是还有另一种方法可以做完全相同的事情.我缺少的两种方法有什么不同吗?
I've been using the 'include?' method since I first started using Rails, so it's intriguing that there's another method that does exactly the same thing. Is there's some difference in the two methods that I'm missing?
编辑
是否有使用in"的场景?会比使用包含"受益更多吗??因为现在,我能想到的就是在?"给出'include'是一种相当无意义的方法吗?已经为它的目的而存在.
Is there any scenario where using 'in?' would benefit more than using 'include?' ? Because right now, all I can think is that 'in?' is a rather pointless method given 'include?' already exists for its purpose.
推荐答案
in?方法在 Rails 3.1 之后可用.那么如果你想用在呢?方法,我们需要标记 require 'active_support' 那么我们可以使用 in?方法.
in? method is available after Rails 3.1 . So if you want to use in? method, we need to mark require 'active_support' then we can make use of in? method.
但是包括?方法可用于所有枚举.就像在普通的 ruby 控制台中一样,您可以尝试:
But the include? method in available for all Enumerables. Like in your normal ruby console you can try:
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 控制台:
From rails console:
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)
你可以看到,包括?比 in 快吗?
You can see, include? is faster than in?
这篇关于Rails:'in?' 之间的区别?和“包括?"在 Rails 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!