To iterate over a set in Ruby, you can use the each method or a block.
In this example,
string_set
containing various strings.each
method or a block to iterate through each element in the string_set
.require 'set'
string_set = Set.new(['Apple', 'Banana', 'Orange'])
string_set.each do |string|
puts string
end
Apple Banana Orange
In this example,
int_set
containing various integer values.each
method or a block to iterate through each element in the int_set
.require 'set'
int_set = Set.new([1, 2, 3, 4, 5])
int_set.each do |number|
puts number * 2
end
2 4 6 8 10
In this tutorial, we learned How to Iterate Over a Set in Ruby language with well detailed examples.