Skip to main content

Command Palette

Search for a command to run...

Ruby Intersection of Object Arrays

Published
2 min read

By default, arrays of objects cannot be intersected in Ruby. By overriding eql?(other) and hash methods, we can make a Ruby object capable of intersecting.

class Color
  attr_reader :name

  def initialize(name)
    @name = name
  end
end

# Both lists have Blue in common so Blue should be the intersection.
list1 = [Color.new("Blue"), Color.new("Yellow"), Color.new("Black")].shuffle
list2 = [Color.new("Blue"), Color.new("Red"), Color.new("White")].shuffle

# But result is empty.
list1 & list2
#=> []
# Array-intersecting-capable class.
class Color
  attr_reader :name

  def initialize(name)
    @name = name
  end

  def eql?(other)
    other.kind_of?(self.class) && name == other.name
  end

  def hash
    name.hash
  end
end

# Both lists have Blue in common so Blue should be the intersection.
list1 = [Color.new("Blue"), Color.new("Yellow"), Color.new("Black")].shuffle
list2 = [Color.new("Blue"), Color.new("Red"), Color.new("White")].shuffle

# The result is as expected.
list1 & list2
#=> [#<Color:0x007f92001a5c18 @name="Blue">]

Surprisingly there was not much information on this topic. This old article from 2006 was helpful.

That's it.

More from this blog

Raspberry Pi TensorFlow Liteで物体検出を楽しむ

この記事について Raspberry Pi、TensorFlow、Pythonのいずれにも詳しくない筆者が、物体検出をやって楽しんだ成果の記録です。 TensorFlow公式の物体検出のサンプルプログラムを実行します。 動作環境 ボード Raspberry Pi 4 Model B OS Raspberry Pi OS (32-bit または 64-bit) デスクトップ環境 カメラ Raspberry Pi カメラモジュール v2 Python Python ...

Apr 23, 20231 min read

Elixir Circuits.I2C with Mox

This is written in Japanese. I might convert it to English later, maybe. はじめに Elixirのテストでモックを用意するときに利用するElixirパッケージとして、moxが人気です。Elixir作者のJosé Valimさんが作ったからということもありますが、ただモックを用意するだけではなくElixirアプリの構成をより良くするためのアイデアにまで言及されているので、教科書のようなものと思っています。 一言でいうと「その場...

Dec 3, 20213 min read
M

Masatoshi Nishiguchi's Blog

62 posts