LaunchKit
All quizzes
Ruby 0 views

Deduplicating with Array#| and an empty array

Question

What is the return value of the following Ruby code?

[1, 3, 2, 1, 2] | [] # => ???

The correct answer is

Explanation

TL;DR

| on arrays is Array#|, the set union method, not a bitwise OR. It returns a new array containing the elements of both operands, duplicates removed, order of first appearance preserved. Union with an empty array adds nothing but still drops the duplicate 1 and 2, returning [1, 3, 2].

Step by step

[1, 3, 2, 1, 2] | [] # => [1, 3, 2]
[1, 2] | [2, 3]      # => [1, 2, 3]

Elements are compared with eql? and hash, the same equality uniq uses. When deduplication is the only goal, uniq states the intent more directly:

[1, 3, 2, 1, 2].uniq # => [1, 3, 2]

Use cases

Merging user preferences while keeping them unique:

preferences     = ["dark_mode", "font_size"]
new_preferences = ["font_size", "language"]

preferences |= new_preferences
preferences # => ["dark_mode", "font_size", "language"]

Combining tag lists without introducing duplicates:

tags     = ["ruby", "programming", "ruby"]
new_tags = ["rails", "programming", "testing"]

tags | new_tags # => ["ruby", "programming", "rails", "testing"]

Edge cases

To union several arrays at once, Array#union (Ruby 2.6+) takes multiple arguments in a single pass:

[1, 2].union([2, 3], [3, 4]) # => [1, 2, 3, 4]

Share this quiz

Comments

No comments yet. Be the first.

Only used to confirm and publish your comment. Never shown publicly, never shared.

Markdown: **bold**, `code`, ```fenced blocks```, > quotes, [links](url). HTML and images are not rendered.