In Ruby, you can access items in a set using iteration or specific methods provided by the Set data structure.
In this example,
string_set
containing strings.require 'set'
string_set = Set.new(["Apple", "Banana", "Orange", "Grapes"])
string_set.each do |item|
puts item
end
Apple Banana Orange Grapes
In this example,
number_set
containing integers.size
method to get the number of elements in the set.include?
method to check if an item exists in the set.require 'set'
number_set = Set.new([1, 2, 3, 4])
puts "Number of elements: #{number_set.size}"
puts "Does set contain 3? #{number_set.include?(3)}"
Number of elements: 4 Does set contain 3? true
In this tutorial, we learned How to Access Items in a Set in Ruby language with well detailed examples.