Do you think IIT Guwahati certified course can help you in your career?
No
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.
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.
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.
Each
Each with index
Map
Select
Reduce
Inject
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
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
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
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
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
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
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
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
Each
Map
Select
Reduce
Inject
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.