Array union

2747 views

What is the return value of the following Ruby code?

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

The correct answer is

[1, 3, 2, 1, 2, []]

[1, 3, 2]

It raises SyntaxError

[1, 3, 2, 1, 2]

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

This line of Ruby code uses the bitwise OR operator (|) to perform a set union operation on two arrays.

The left array [1, 3, 2, 1, 2] and the right array [] (an empty array) are combined, and duplicate elements are removed.

The result, [1, 3, 2], is a new array containing the unique elements from both arrays.

In this case, it removes the duplicate 1 and 2 from the left array, resulting in [1, 3, 2].

Use Cases

Let's consider more real-life scenarios where the array union idiom in Ruby can be applied.

User Preferences

user.preferences         # => ['dark_mode', 'font_size']
params[:new_preferences] # => ['font_size', 'language']

user.preferences |= new_preferences # => ['dark_mode', 'font_size', 'language']

When a user updates its preferences, the | operator helps merge the existing and new preferences, ensuring that only unique preferences are stored.

Tagging System

article.tags = ['ruby', 'programming', 'ruby']
new_tags = ['rails', 'programming', 'testing']

article.tags = article.tags | new_tags # => ['ruby', 'programming', 'rails', 'testing']

In a tagging system for articles, combining existing tags with new tags using | ensures that each tag is unique in the final set.

Conclusion

In these examples, the array union operation helps maintain uniqueness and prevents redundant data, which is common in scenarios involving preferences, tags, inventory, or user registrations.

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©