Codectionary / Developer documentation / Ruby

Sets and Set Operations

Set stores unique elements and supports union, intersection and difference. On Ruby 3.x, require set before use. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

Syntax

Set.new(values); first & second; first - second

Examples

Sets and Set Operations

Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

require "set"
available = Set.new(%w[tea coffee tea])
requested = Set.new(%w[tea cocoa])
puts available.size
p (available & requested).to_a.sort
p (requested - available).to_a.sort
  1. Expected output: 2 ["tea"] ["cocoa"]
  2. The repeated tea is stored once. Intersection finds fulfilled requests, while difference identifies unavailable items. Sorting makes the displayed order explicit.

Best practices

  • Use Set when membership and uniqueness matter more than numeric position.
  • Avoid changing the hash/eql? behavior of elements while they are stored in a set.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

Specifications & further reading