Syntax
Set.new(values); first & second; first - secondExamples
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- Expected output: 2 ["tea"] ["cocoa"]
- 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