I was going to write up another method in the Ruby standard library, but was going to use the include?
in some of the examples, so I decided I should just start with include?
.
The #include?
method is part of the Enumerable
module, and when passed and object, it returns true
if the object is in the enum.
This works not only for arrays:
[1, 2, 3, 5, 8, 13, 21].include? 4 #=> false [1, 2, 3, 5, 8, 13, 21].include? 5 #=> true
But also strings:
'banana'.include? 's' #=> false 'banana'.include? 'a' #=> true
And maps:
{a: 1, b: 2, c: 3}.include? :a #=> true {a: 1, b: 2, c: 3}.include? :q #=> false {a: 1, b: 2, c: 3}.include? 1 #=> false
Which if you notice checks if the object is one of the keys in the map.
And because it uses the ==
operator, it works on coercing datatypes, so we are able to find a floating point version of a number in a list of integers:
[1, 2, 3, 5, 8, 13, 21].include? 1.0 #=> true [1, 2, 3, 5, 8, 13, 21].include? 1.1 => false
And the beauty of this is that if you want this behavior on one of your classes or modules, you just include the Enumerable
module and implement the #each
method, and the Enumerable
module will take care of this behavior for you.