Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 833
adnann Avatar asked Feb 02 '15 07:02

adnann


People also ask

What is the difference between include and require in Ruby?

The include method takes all the methods from another module and includes them into the current module. This is a language-level thing as opposed to a file-level thing as with require. The include method is the primary way to "extend" classes with other modules (usually referred to as mix-ins).

What is the difference between extend and include in Ruby?

In simple words, the difference between include and extend is that 'include' is for adding methods only to an instance of a class and 'extend' is for adding methods to the class but not to its instance.

What is exclude in Ruby?

The exclude_end?() is an inbuilt method in Ruby returns boolean value true if the range excludes its end value, else it returns false.


1 Answers

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?

like image 182
Ajay Avatar answered Sep 30 '22 10:09

Ajay