To create a set of numbers from 1 to N in Ruby, you can use a Hash or Set data structure where the keys or elements represent the numbers.
In this example,
number_set
.add
method of the Set object.require 'set'
number_set = Set.new
(1..5).each do |i|
number_set.add(i)
end
puts 'Set of numbers from 1 to 5:', number_set.inspect
Set of numbers from 1 to 5: #<Set: {1, 2, 3, 4, 5}>
In this example,
number_set
.add
method of the Set object.require 'set'
number_set = Set.new
(1..10).each do |i|
number_set.add(i)
end
puts 'Set of numbers from 1 to 10:', number_set.inspect
Set of numbers from 1 to 10: #<Set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}>
In this tutorial, we learned How to create a Set of Numbers from 1 to N in Ruby language with well detailed examples.