Difference between 'in?' and 'include?' in Rails

怎甘沉沦 提交于 2019-12-05 18:48:41

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.

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

From rails console:

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

Check their performance:

 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)

You can see, include? is faster than in?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!