Ruby Array Set Operations

Array Set Operations in Ruby

Performing array set operations in Ruby and introducing examples with Ruby on Rails models. Performing array operations from Ruby language for intersection, union, and difference.

Shou Arisaka
1 min read
Nov 24, 2025

Performing array set operations in Ruby and introducing examples with Ruby on Rails models. Performing array operations from Ruby language for intersection, union, and difference.

For example, a list of web pages containing both of multiple keywords is finding the intersection, and a list of web pages containing any of multiple keywords is finding the union.
``` p a & b # Intersection p a | b # Union p a - b # Difference
[Ruby: How to perform set operations? - Build Insider](https://www.buildinsider.net/language/rubytips/0025)

Here's a specific example in Rails.
```ruby

Hashmodel.where(title:"title").ids
=> [1, 2]

Hashmodel.tagged_with("fuga").by_join_date.ids
=> [6, 1]

# Get the id of hashmodel whose title is "title" and has the tag "fuga" (intersection)
Hashmodel.where(title:"title").ids & Hashmodel.tagged_with("fuga").by_join_date.ids
=> [1]

# Union; find the case when OR search is performed
Hashmodel.where(title:"title").ids | Hashmodel.tagged_with("fuga").by_join_date.ids
=> [1, 2, 6]

# By the way, using `+` results in merged arrays. Since values are duplicated, it's not a union.
Hashmodel.where(title:"title").ids + Hashmodel.tagged_with("fuga").by_join_date.ids
=> [1, 2, 6, 1]

Ruby: How to perform set operations? - Build Insider also introduces the Jaccard coefficient for finding set similarity. You might want to read it if youโ€™re interested.

Share this article

Shou Arisaka Nov 24, 2025

๐Ÿ”— Copy Links