Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 27 / 68

Working with Set

In this lesson you will learn to manage duplicate-free data and search it quickly with Ruby's Set class. This is for anyone searching for "Ruby Set how to use".

Set, available after require 'set', is a box that refuses to hold the same value twice. It is handy for stripping duplicates out of an array, or for checking membership quickly.

The sample code builds a duplicate-free Set from the array nums with Set.new(nums), then converts back with .to_a.sort to print it in order. You can also check membership with .include?(2).

A common stumbling block for beginners is forgetting require 'set'. Unlike Array and Hash, Set has to be loaded explicitly, and leaving it out is an error.

It brings the mathematical idea of a set straight into code, which is very handy for removing duplicates. It comes up often for things like de-duplicating tags selected in a form.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)