Skip to content

Instantly share code, notes, and snippets.

@pasberth
Created September 16, 2011 15:04
Show Gist options
  • Select an option

  • Save pasberth/1222316 to your computer and use it in GitHub Desktop.

Select an option

Save pasberth/1222316 to your computer and use it in GitHub Desktop.
指定したメンバがすべて同値の場合に == が true を返す attr_reader みたいな
class Class
def iffattrs *attrs
define_method(:==) do |other|
attrs.each do |attr|
symbol = :"@#{attr}"
return false if instance_variable_get(symbol) != other.instance_variable_get(symbol)
end
true
end
end
end
if __FILE__ == $PROGRAM_NAME
require "test/unit"
class SampleClass
def initialize name, age
@name = name
@age = age
end
iffattrs :name, :age
end
class TestIffattrs < Test::Unit::TestCase
def test_iffattrs
assert_equal SampleClass.new("Yae", 16), SampleClass.new("Yae", 16)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment