Search code examples
ruby-on-railsactivesupport

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


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])

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?

EDIT

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.


Solution

  • 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?