DEV Community

Toni Oriol
Toni Oriol

Posted on • Originally published at Medium on

1 1

Difference, Union and Intersection in Ruby arrays

It’s done with basic operators instead of methods: - for difference, | for union, and & for intersection.

An important detail is that all duplicated items are automatically removed. Which allows to make an array unique finding the intersection between itself: [1, 1, 2] & [1, 1, 2] = [1, 2].

Difference

[1, 2, 3] - [3, 4, 5] = [1, 2]

[3, 4, 5] - [1, 2, 3] = [4, 5]

In summary, it returns the unique values only present in the first array.

Union

[1, 2, 1, 2, 3] | [1, 2, 3, 4] = [1, 2, 3, 4]

Intersection

[1, 1, 3, 5] & [1, 2, 3] = [1, 3]

Source: https://www.endpoint.com/blog/2011/06/07/using-set-operators-with-ruby-arrays

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay