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.
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).
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.
The exclude_end?() is an inbuilt method in Ruby returns boolean value true if the range excludes its end value, else it returns false.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With