Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Objects in Ruby
2.1.
Example
2.1.1.
Output
2.1.2.
Explanation
3.
Iterators in Ruby
3.1.
Example
3.1.1.
Output
4.
Problem Statement 
5.
Changing the Way an Object Iterates in Ruby
6.
Enumerable Module
6.1.
Example of Any
6.1.1.
Output
6.2.
Example of Cycle
6.2.1.
Output
6.3.
Example of All
6.3.1.
Output
6.4.
Example of Each Iterator
6.4.1.
Output
6.4.2.
Explanation
7.
Frequently Asked Questions
7.1.
What is Ruby?
7.2.
What is an iterator in Ruby?
7.3.
What are objects in Ruby?
7.4.
Why is there a need to change the way an object iterates in ruby?
7.5.
What are the different types of iterators in Ruby?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Changing the Way an Object Iterates in Ruby

Author Ayushi Goyal
0 upvote

Introduction

Ruby is a high-level, interpreted, and object-oriented programming language that is general-purpose, dynamic, and reflective. Except for blocks, which have replacements in the form of procs and lambda, everything in Ruby is an object. The goal of Ruby’s development was to create a user interface between human programmers and the computational machinery that underpins them.

Introduction to ruby

Ruby’s syntax is similar to many other programming languages, including C and Java, making learning easy for Java and C programmers. It runs on various OS(Operating Systems), including Windows, Mac OS X, and Linux.

Let’s talk about the objects in ruby and then the process of changing how an object iterates.

Objects in Ruby

Ruby is an object-oriented programming language involving the concept of classes and objects. Objects are the instance of a class. In ruby, objects can be created using the ‘new’ method of a class, a pre-defined method in Ruby. 

The syntax for creating an object is -  

object_name = class_name.new
 

You can also customize this new method by passing parameters, which can be used to initialize the class variables. For that, we have to create a method named ‘initialize’, which is executed every time the ‘new’ method is called. 

Example

class Student
   def initialize(id, name, course)
      @student_id = id
      @student_name = name
      @student_course = course
   end
   
   def show
       print "\nStudent Name - " 
       print @student_name
   end
end

obj = Student.new("1","Ninja1","CSE")
obj2 = Student.new("2","Ninja2","EE")
print "List of Students studying in Coding Ninjas:\n"
obj.show
obj2.show
You can also try this code with Online Ruby Compiler
Run Code

Output

Output of objects

Explanation

In this code, we created two objects, ‘obj’ and ‘obj2’, using the ‘new’ method and passed parameters to the ‘new’ method. Then, the student’s name was printed using the ‘show’ method defined in the ‘Student’ class.

Iterators in Ruby

Iteration refers to doing one thing many times. Iterators are object-oriented concepts and are used for performing these iterations in Ruby. Iterators are supported by collections(Arrays, Hash, etc.) in Ruby and help return all the collection elements. The syntax for defining an iterator is

collection.iterator do |variable|
	# Statement
end
You can also try this code with Online Ruby Compiler
Run Code

Example

array = [1,2,3,4,5]
print "Iterator result - \n"
array.each do |var|
   print var
   print " "
end
You can also try this code with Online Ruby Compiler
Run Code

Output

output of iterators

Problem Statement 

Problem statement

We have already learned about what are objects and iterators. So now come to the main topic, i.e., changing the way an object iterates in ruby. Sometimes iterator doesn’t iterate the way we want. 

For example - if we want to collect array elements in reverse order, then we have to change the way of the ‘collect’ iterator on the array. 

Changing the Way an Object Iterates in Ruby

The problem of changing the way an object iterates in ruby can be solved by wrapping up the objects in an Enumerator.

Enumerable is a Ruby class that allows internal (Controlled by class) and external (Controlled by user) iterations. It is an implementation of a basic iterator design. 

Enumerable Module

Ruby offers an enumerable module that contains methods like count, map, select, uniq, and include. Most of these methods are associated with heap and arrays. These methods focus on searching, traversing, sorting, etc., operations.

The ‘each’ iterator is also an important pillar of this enumerable module, which takes a list as its first argument and a block of code as its second argument. Apart from the ‘each’ iterator, it also provides three other important methods. These are any, cycle, and all. 

Any - This method returns true if any element block passed to it is true.

Cycle - Used for traversing the entire collection endlessly.  

All - This method returns true if all element block passed to it is true.

Example of Any

enum = [10, 19, 18]
result = enum.any? { |num| num>13}

# Prints the result
print "Any number greater than 13 : " 
print result

result2 = enum.any? { |num| num>=20}

# Prints the result
print "\nAny 
number greater than 20 : "
print result2
You can also try this code with Online Ruby Compiler
Run Code

Output

Output of Any

Example of Cycle

# Declaring array
a = ["Coding", "Ninja"]

# Cycling the array elements 2 times
puts "CYCLE - "
puts "#{a.cycle(2){ |x| puts x }}\n"
You can also try this code with Online Ruby Compiler
Run Code

Output

Output of Cycle

Example of All

# Initialize an enumerable
enum = [10, 19, 18]

# Checks if all numbers are greater than 4 or not
result1 = enum.all? { |num| num>4}
print "All numbers are greater than 4 : "
puts result1

# Checks if all numbers are >= 15 or not
result2 = enum.all? { |num| num>=15}
print "All numbers are >= 15 : "
puts result2
You can also try this code with Online Ruby Compiler
Run Code

Output

Output of All

Example of Each Iterator

array = %w{Coding Ninja is Best}
reverse_array = array.to_enum(:reverse_each)
reverse_array.collect { |x| }
reverse_array.each_with_index do |x, i|
	puts %{#{i}=>"#{x}"}
end
You can also try this code with Online Ruby Compiler
Run Code

Output

Output of each

Explanation

In this code, we have created an array, and to transverse the array in reverse order, we have created a 'reverse_array' iterator using an enumerable module.

Hopefully, you understood the solution of changing how an object iterates in ruby. 

Frequently Asked Questions

What is Ruby?

Ruby is a high-level, interpreted, general-purpose programming language that supports multiple programming paradigms.

What is an iterator in Ruby?

Iterators are object-oriented concepts and are used for performing these iterations in Ruby. Iterators are supported by collections and help in returning all the elements of a collection.

What are objects in Ruby?

Objects are the instance of a class. In ruby, objects can be created using the ‘new’ method of a class, a pre-defined method in Ruby.

Why is there a need to change the way an object iterates in ruby?

Sometimes iterator doesn’t iterate the way we want; at that time, there is a need to change the way an object iterates in ruby. 

What are the different types of iterators in Ruby?

There are various iterators in ruby: each, collect, step, times, upto, each_line and downto. 

Conclusion

This blog covered the details on changing the way an object iterates in ruby. We learned what objects and iterators are, how to define iterators, and the process of changing the way an object iterates in ruby, along with examples.

If you want to learn more, check out our articles/blogs on ruby and refer to Ruby Documentation for more information. You can also learn more about ruby from the links given below.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, JavaScript, System Design, etc. Enroll in our courses like Competitive Programming and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Thank you

Do upvote our blog to help other ninjas grow. 

Happy Learning Ninja! 🐱‍👤

Live masterclass