==を定義するモジュール

30分プログラム、その133。毎回、似た==メソッドが面倒なので、モジュールを作ってみた。

例えば、次のようなクラスの場合、

class Hoge
  def initialize(a,b)
    @a = a
    @b = b
  end
end

こんな感じの==メソッドを定義する。

class Hoge
  attr_reader :a,:b
  def ==(o)
    o.class == Hoge and
     o.a == self.a and o.b == self.b
  end
end

これが面倒なので、

class Hoge
  include Equals
  def initialize(a,b)
    @a = a
    @b = b
  end
end

で済むようにしてみた。

使い方

$ ruby equals.rb
#<Hoge:0x41a4b0 @a=1, @c=3, @b=2> == #<Foo:0x41a3fc @a=1, @c=3, @b=2> -> false
#<Hoge:0x41a4b0 @a=1, @c=3, @b=2> == #<Hoge:0x41a474 @a=1, @c=4, @b=2> -> false
#<Hoge:0x41a4b0 @a=1, @c=3, @b=2> == #<Hoge:0x41a438 @a=1, @c=3, @b=2> -> true

ソースコード

#! /opt/local/bin/ruby -w
# -*- mode:ruby; coding:utf-8 -*-
#
# equals.rb -
#
# Copyright(C) 2007 by mzp
# Author: MIZUNO Hiroki <hiroki1124@gmail.com>
# http://mzp.sakura.ne.jp/
#
# Timestamp: 2007/09/14 19:49:22
#
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Ruby itself.
#
module Equals
  def ==(o)
    self.class == o.class and
      (self.instance_variables | o.instance_variables).all?{|id|
      self.instance_variable_get(id) == o.instance_variable_get(id)
    }
  end
end

class Object
  include Equals
end

class Hoge
  def initialize(a,b,c)
    @a = a
    @b = b
    @c = c
  end
end

class Foo
  def initialize(a,b,c)
    @a = a
    @b = b
    @c = c
  end
end

hoge1 = Hoge.new 1,2,3
hoge2 = Hoge.new 1,2,4
hoge3 = Hoge.new 1,2,3
foo = Foo.new 1,2,3

[[hoge1,foo],[hoge1,hoge2],[hoge1,hoge3]].each{|lhs,rhs|
    puts "#{lhs.inspect} == #{rhs.inspect} -> #{lhs == rhs}"
}