Table of contents
1.
Introduction
2.
Statement and Control Structures
3.
Iterators and Enumerable Objects
4.
Enumerators in Ruby
4.1.
Each Enumerator in ruby
4.2.
Each with index enumerator in ruby
4.3.
Map Enumerator in ruby
4.4.
Select Enumerator in ruby
4.5.
Reduce Enumerator in ruby
4.6.
Inject Enumerator in ruby
4.7.
Collect Enumerator in ruby
5.
Frequently Asked Questions
5.1.
What is Ruby?
5.2.
What are enumerators in ruby?
5.3.
Some of the enumerators in ruby
5.4.
What is an iterator in ruby?
5.5.
Is Ruby Case Sensitive?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Enumerators in Ruby

Author Gaurav joshi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In our day-to-day life, we make a lot of decisions. Our life is not simple as a program executing sequentially. A sequential program is one where lines of code are executed one after the other without branching or repetition. It’s simple, but any program could rarely be that simpler.

Enumerators in Ruby

Like in our lives, we make a decision based on a particular condition. We have to identify a way in ruby of telling the computer to conditionally execute some code: to execute it only if some condition is satisfied. One such way is an enumerator in ruby. We will understand all about an enumerator in ruby in this article but before that, have a brief introduction to statement and control structures.

Statement and Control Structures

So as we already explained, having a simple program that consists primarily of method invocations and variable assignment is rare. What makes such a program particularly simple is its purely sequential execution. Program is executed one after the other without branching or repetition. It is rare seeing any program for being that simple. An Enumerator in ruby tells the computer to conditionally execute some line of the code only if some condition is satisfied and hence to follow a control structure.

This image describe types of control structures like conditionals and repetition

PROGRAMME CONTROL STRUCTURE

Iterators and Enumerable Objects

Although loops constitute a significant part of the Ruby language for defining program control structure, it is probably more common to write loops rather than using unique methods called iterators. Iterators in ruby are one of the most noteworthy features of Ruby and help us in defining the control structure of ruby. We use the term iterator to mean any yield statement method. They do not serve the purpose of an iteration or looping function. For example, data structures like Array, Hash, Range, and several other classes define each iterator that passes each collection element to the associated block.

Similarly, an Enumerable object is one whose purpose is to enumerate over some other object. Now that you got a brief understanding of iterators and enumerable objects in ruby, let's get to the main discussion. The Enumerator in ruby. Now down the section, we will be getting to know Enumerator in ruby in detail.

Enumerators in Ruby

An Enumerator in ruby is a class that allows iterations of both types – external and internal. Internal iteration is when the class in question controls iteration, while external iteration is when the environment or the client controls iteration. While Enumerable is getting all the required attention, Enumerator in ruby is also more creditworthy for doing amazing things in their own way. Well, it's time to take notice. So in simpler terms, Enumerator in ruby is a class which allows both internal and external iteration.

The following methods could help us create an Enumerator.

  • Kernel#to_enum
  • Kernel#enum_for
  • :: new
     

Now let's see some of the Enumerator in ruby, i.e., some of the Enumerable instance methods.

  1. Each 
  2. Each with index
  3. Map
  4. Select
  5. Reduce
  6. Inject
  7. Collect

Each Enumerator in ruby

Each Enumerator is defined on Array, Hash, Range and several classes that pass each collection element to the associated block. Each Enumerator in ruby is not only defined for traditional "data structure" classes. Even Ruby's IO class defines each iterator that yields lines of text read from the Input/Output object. Most of the classes that define each method include an Enumerable module. The enumerable module defines many more specialised iterators implemented on top of each method. One such helpful iterator is each_with_index, which allows us to add line numbering and are going to discuss next.

CODE

# Initialising an array
sample_array = ['Coding', 'Ninja', 'Is', 'Best'] 
  
# Calling the each function
C = sample_array.each { |sample| print sample + "\n" } 
  
# Getting the values of the array
puts "#{C}"
You can also try this code with Online Ruby Compiler
Run Code

 

OUTPUT

Coding
Ninja
Is
Best
["Coding", “Ninja, ”Is", “Best”]
You can also try this code with Online Ruby Compiler
Run Code

Each with index enumerator in ruby

Each_with_index() enumerator in ruby is an inbuilt function that hashes out the items in the enumerable according to the given block. The each_with_index() function takes the block, which initialises the index to the individual objects. each_with_index() returns the Enumerator if no block is given; else, it hashes the items.

CODE

# each_with_index enumerator in ruby or method in Enumerable
  
# Initialize 
hashing = Hash.new
enu = [7, 9, 10]
  
enu.each_with_index { |item, index|
  hashing[item] = index
}
  
# prints hash
puts hashing
You can also try this code with Online Ruby Compiler
Run Code

 

OUTPUT

{"Coding"=>0, “Ninja”=>1, “Is”=>2, “Best”=>3}
You can also try this code with Online Ruby Compiler
Run Code

Map Enumerator in ruby

Map () enumerator in ruby is an inbuilt method. It returns a new array with the results of executing block once for every element in the enum. The objects are recited for each enum every time. In case no object is given, it returns nil for each enum.

CODE 

# Implementation of map enumerator in ruby
# Returns an array to the enumerator
enumerator = (10..20).map {|x| x * 2}
print enumerator
You can also try this code with Online Ruby Compiler
Run Code

 

OUTPUT 

[20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40]
You can also try this code with Online Ruby Compiler
Run Code

Select Enumerator in ruby

Select Enumerator in ruby gives items in the block selected by block, .i.e, those elements of block for which the block returns a TRUE value. It returns an array collecting all elements of an enum which fulfilled the condition. If no block is discovered, it returns an enumerator instead.

CODE

# Implementation of select Enumerator in ruby
  
# Initialise 


# Include all in range1 till 10 both 1 and 10 included
enumerator = (1..10)
  
# Prints only which satisfies condition
print enumerator.select { |obj| obj % 3 == 0}

You can also try this code with Online Ruby Compiler
Run Code


OUTPUT 

[3, 6, 9]
You can also try this code with Online Ruby Compiler
Run Code

Reduce Enumerator in ruby

Reduce() Enumerator Combines elements present in the enum by applying a simple binary operation specified by a block or a symbol. The inject() method acts somewhat similar to the reduce() method. They both are aliases.

CODE

# Implementation of reducing Enumerator in ruby
  
# Sum, without initial_operand.
enumerator_1 = (5..10).reduce(:+)     # => 45
puts enumerator_1
# Sum, with initial_operand.
enumerator_2 = (5..10).reduce(10, :+) # => 55
puts enumerator_2
You can also try this code with Online Ruby Compiler
Run Code


OUTPUT

45
55
You can also try this code with Online Ruby Compiler
Run Code

Inject Enumerator in ruby

Inject Enumerator Combines elements present in the enum by applying a simple binary operation specified by a block or a symbol. The inject() method acts somewhat similar to the reduce() method.

CODE

# Implementation of inject Enumerator in ruby
  
# Sum, without initial_operand.
enumerator_1 = (5..10).inject(:+)     # => 45
puts enumerator_1
# Sum, with initial_operand.
enumerator_2 = (5..10).inject(10, :+) # => 55
puts enumerator_2
You can also try this code with Online Ruby Compiler
Run Code


OUTPUT

45
55
You can also try this code with Online Ruby Compiler
Run Code

Collect Enumerator in ruby

Collect Enumerator in ruby is a built-in method that gives a new array with the results of executing a block once for every element in given enum. Collect() takes object and block for every enum, and it also takes r1 and r2  and returns a new array. In case no object is given, it returns nil for each enum.

CODE

# Implementation of collect enumerator in ruby
# returns an array to the enumerator
enumerator = (10..20).collect {|x| x * 2}
print enumerator
You can also try this code with Online Ruby Compiler
Run Code

 

OUTPUT

[20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40]
You can also try this code with Online Ruby Compiler
Run Code

Frequently Asked Questions

What is Ruby?

Ruby is an open-source dynamic language with natural and easy-to-read/write syntax. Ruby is a careful balance language and a perfect blend of five different languages.

What are enumerators in ruby?

An enumerator in ruby is a class that allows iterations of both types – external and internal. Internal iteration is when the class in question controls iteration, while external iteration is when the environment or the client controls iteration.

Some of the enumerators in ruby

Enumerators in ruby is also known as Enumerable instance methods. Some of the examples of enumerators in ruby are 

  1. Each 
  2. Map
  3. Select
  4. Reduce
  5. Inject
  6. Collect

What is an iterator in ruby?

Iterators in ruby are one of the most noteworthy features of Ruby and help us in defining the control structure of ruby. Iterator in ruby passes each collection element to the associated block.

Is Ruby Case Sensitive?

Ruby is a case-sensitive language, which means lowercase identifiers in ruby are different from uppercase identifiers. E.g. Like_This is entirely different from LIKE_THIS. Similarly, Start is different from START.

Conclusion

In this article, we have studied enumerators in Ruby in detail and briefly explored some of the enumerators in ruby along with the code. We expect that this article must have helped you enhance your knowledge on the topic of Ruby. Do upvote our blog to help other ninjas grow.

Also, visit our Guided Path in  Coding Ninjas Studio to learn about  Ruby. If you are preparing for an interview, visit our Interview Experience Section and interview bundle for placement preparations. Upskill yourself in Ruby on RailsBackend Web TechnologiesHadoopSQL, MongoDB, Data Structures and Algorithms, JavaScript,  System Design and much more!. Please upvote our blogs if you find them engaging and helpful! I wish you all the best for your future adventures and Happy Coding. 

Useful links: Operational DatabasesNon- relational databasesMongoDBTop-100-SQL-problemsinterview-experienceIntroduction to ruby on railsDirectory Structure in RubyRuby on RailsRuby vs Python

You can also refer to the Official RubyRubyOfficial DocumentationRuby FAQRuby KoansRuby DocWhy Ruby?

Live masterclass