Everything is “Enumerable” in Ruby
Welcome 😀
Good day, dear coders, enthusiasts, and just reader guests!
Here I am with a new bit of coding tip about precious Ruby. Today, we are going to pick up a little info about using the “Enumerable” module of Ruby and mixing it into a user-defined class.
We will also bring some examples about the features and possibilities it brings to the new class and how it simplifies iterating through elements of the new class.
So, fasten your seat belts and here we go…
What is the “Enumerable” module in Ruby?
Enumeration refers to traversing over objects. In Ruby, we call an object enumerable when it describes a set of items and a method to loop over each of them.
“Enumerable” is a collection of iteration methods, a Ruby module, and a big part of what makes Ruby a great programming language.
Also, few important Ruby classes include this module, such as theArray
, Hash
, Range
classes.
Enumerable includes helpful methods like:
- map : transforms all the values,
- select : filters the given list,
- inject : used to add up all the values inside an array
Enumerable methods work by giving them a block.
In that block, you tell them what you want to do with every element.
For example:
[1,2,3].map { |n| n * 2 }
Returns a new array where every number has been doubled.
Exactly what happens depends on what method you use, map
helps you transform all the values, select
lets you filter a list & inject
can be used to add up all the values inside an array.
There are over 20 Ruby Enumerable methods.
So, here’s the list of methods that the “Enumerable” module provides us with, when mixed into a new class: https://ruby-doc.org/core-3.0.1/Enumerable.html
How do we use it?
The Enumerable
module relies on a method named #each
, which needs to be implemented in any class it’s included in. When called with a block on an array, the #each
method will execute the block for each of the array’s elements.
class Students
include Enumerable
def initialize
@students = %w[Marat John Mark]
end def each
for student in @students do
yield student
end
end
end group_students = Students.newgroup_students.map { |student| student.upcase } # => ["MARAT", "JOHN", "MARK"]
Here, we implemented ‘each’ method on a class “Students”, and mixed in “Enumerable” module, to be able to traverse over it.
Conclusion 👋
And finally we’ve come to the end of this short article about “Enumerable” module and learned something new to be able to add extra features to the user-defined class.
In the end, let’s take a look at a quote told by Yukihiro Matz (creator of Ruby), about what he was inspired by, while developing magical Ruby.
Sometimes people jot down pseudo-code on paper. If that pseudo-code runs directly on their computers, it’s best, isn’t it? Ruby tries to be like that, like pseudo-code that runs. Python people say that too.
Yukihiro Matsumoto
Bye !!!