【问题标题】:Rails: Difference between 'in?' and 'include?' in RailsRails:“在?”之间的区别和“包括?”在 Rails 中
【发布时间】:2015-04-01 02:13:33
【问题描述】:

我在浏览 Rails 的 ActiveSupport 扩展时遇到了“in?”方法。对我来说,它的外观和工作方式与“包含?”完全一样。方法,但正好相反。

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

我一直在使用“包含?”自从我第一次开始使用 Rails 就开始使用这种方法,所以有趣的是,还有另一种方法可以做同样的事情。我缺少的两种方法有什么不同吗?

编辑

有没有使用'in'的场景?会比使用“包含”更受益吗? ?因为现在,我所能想到的就是“在?”给定“包含”是一个相当无意义的方法吗?已经存在。

【问题讨论】:

  • include? 是一个 ruby​​ 数组方法,而 ` in? ` 是 rails activesupport 方法

标签: ruby-on-rails activesupport


【解决方案1】:

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

但是包含?方法适用于所有 Enumerables。就像在您的普通 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)

你可以看到,包括?比 in 快吗?

【讨论】:

  • 感谢您的全面回答。我想知道是否可以澄清一件事。有没有使用'in'的场景?会比使用“包含”更受益吗? ?因为现在,我所能想到的就是“在?”给定“包含”是一个相当无意义的方法吗?已经为其目的而存在。
  • @adnann 包括?是比 in 更好的选择吗?
  • @adnann 只是检查我的答案,我用这两种方法的性能比较更新了它。希望它有所帮助:)
  • 谢谢!你的回答很可靠。所以在?毕竟方法是没有意义的。
  • 非常有用的见解。
猜你喜欢
  • 2010-11-03
  • 2016-01-07
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-12
相关资源
最近更新 更多