×

Ruby Tutorial

Ruby Basics

Ruby Control Statements

Ruby Methods

Ruby Classes and Methods

Ruby Arrays

Ruby Sets

Ruby Strings

Ruby Classes & Objects

Ruby Hash

Ruby Tools

Ruby Functions

Ruby Built-in Functions

Misc.

Ruby Programs

Ruby program to get the items from a set using 'for' loop

Last Updated : December 15, 2025

Problem Solution

In this program, we will create the object of the Set class. Then we will add the elements into the set using add() method of the Set class and print the set items using the "for" loop.

Program/Source Code

The source code to get the items from a set using the "for" loop is given below. The given program is compiled and executed successfully.

# Ruby program to get the items from 
# a set using "for" loop

require 'set';

setObj = Set.new();

setObj.add(101);
setObj.add(102);
setObj.add(103);
setObj.add(104);
setObj.add(105);

puts "Set elements: ";
for item in setObj
   print item," ";
end

Output

Set elements: 
101 102 103 104 105 

Explanation

In the above program, we imported the "set" package using the "require" statement. Then we created the object setObj of the Set class using the new() method and, we added 5 integer items into created set using add() method of the Set class. After that, we accessed the items from the set using the "for" loop and printed them.

Ruby Set Programs »


Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.