In Ruby, you can use the Set class to represent a Set. To add an item to a Set, you can use the add method provided by the Set class.
In this example,
numbers
containing some integer elements.numbers
to add a new integer element, such as 6
, to the set.numbers
contains the added element 6
.require 'set'
numbers = Set.new([1, 2, 3, 4, 5])
numbers.add(6)
puts "Numbers: { " + numbers.to_a.join(' ') + " }"
Numbers: { 1 2 3 4 5 6 }
In this example,
fruits
containing some string elements.fruits
to add a new string element, such as 'Orange'
, to the set.fruits
contains the added element 'Orange'
.require 'set'
fruits = Set.new(['Apple', 'Banana', 'Cherry'])
fruits.add('Orange')
puts "Fruits: { " + fruits.to_a.join(' ') + " }"
Fruits: { Apple Banana Cherry Orange }
In this tutorial, we learned How to add an Item to a Set in Ruby language with well detailed examples.