Ruby Convert Array to Set

1. Introduction

When working with Ruby, you might find yourself in a situation where you need to ensure that a collection of items contains no duplicates, or you require more efficient membership checking than an array can provide. This is where a set becomes useful. In this post, we'll explore how to convert an array into a set in Ruby.

In Ruby, a set is a collection of unordered values where each value is unique. Unlike arrays, sets do not store duplicate values. Ruby's standard library provides a Set class that implements these collections.

2. Program Steps

1. Ensure the Set class is available by requiring Ruby's set library.

2. Define the array you want to convert into a set.

3. Convert the array into a set using the Set class.

4. Output the new set to show its contents.

3. Code Program

# Step 1: Require the set library
require 'set'
# Step 2: Define the array
array = [1, 2, 2, 3, 4, 4, 5]
# Step 3: Convert the array into a set
set = Set.new(array)
# Step 4: Output the new set
puts set.inspect

Output:

#<Set: {1, 2, 3, 4, 5}>

Explanation:

1. require 'set' ensures that the Set class is available in our script.

2. array is defined with some duplicate elements to illustrate the uniqueness enforced in a set.

3. Set.new(array) creates a new set from the array, automatically removing any duplicate elements.

4. puts set.inspect is used to output the elements of the set. Since sets enforce uniqueness, the duplicates from the original array are not present.


Comments