Ruby Sets

Anonymous contributor's avatar
Anonymous contributor
Published Jul 30, 2021Updated May 15, 2024
Contribute to Docs

In Ruby, a Set is a collection of unordered, non-duplicated values. They are functional like an Array but have quick lookup with Hash-storage.

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn to program in Ruby, a flexible and beginner-friendly language used to create sites like Codecademy.
    • Beginner Friendly.
      9 hours

Syntax

In order to use Sets:

  1. Import the set module with require()
  2. Use the Set keyword followed by brackets ([]) containing comma-separated values
require("set")
test_set = Set[1, 2]
puts test_set # Output: #<Set: {1, 2}>

Example

Values can be added to Sets with #add():

test_set.add("It's a Beautiful Day!")
puts test_set

They can also be deleted with #delete(). Pass in the actual value. If the value doesn’t exist in the Set, nothing happens to it:

test_set.delete(2)
puts test_set # Output: #<Set: {1, "It's a Beautiful Day!"}>
test_set.delete(100)
puts test_set # Output: #<Set: {1, "It's a Beautiful Day!"}>

Since Sets are array- and hash-like, they are iterable and can use methods like each:

require("set")
test_set = Set[1, 2]
test_set.add(3)
test_set.add("It's a Beautiful Day!")
test_set.each do |element|
puts element
end

All contributors

Contribute to Docs

Learn Ruby on Codecademy

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn to program in Ruby, a flexible and beginner-friendly language used to create sites like Codecademy.
    • Beginner Friendly.
      9 hours