Created
September 16, 2011 15:04
-
-
Save pasberth/1222316 to your computer and use it in GitHub Desktop.
指定したメンバがすべて同値の場合に == が true を返す attr_reader みたいな
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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