To get the size of a set in Ruby, you can use the size
method on the set.
In this example,
set1
using the Set
class with some elements.size
method on the set object set1
to get the number of elements in the set.size
method returns the size of the set.require 'set'
set1 = Set.new(['apple', 'banana', 'cherry'])
# Get the size of the set
size = set1.size
# Print the size
puts "Size of set1: #{size}"
Size of set1: 3
In this example,
empty_set
using the Set
class.size
method on the set object empty_set
to get the number of elements in the set.size
method returns 0.require 'set'
empty_set = Set.new
# Get the size of the empty set
size = empty_set.size
# Print the size
puts "Size of empty_set: #{size}"
Size of empty_set: 0
In this tutorial, we learned How to Get Length of a Set in Ruby language with well detailed examples.