Ruby

2つのオブジェクトを全インスタンス変数の値で比較する

More than 3 years have passed since last update.

class User

attr_reader :first_name, :last_name, :group

def initialize(first_name, last_name, group)
@first_name = first_name
@last_name = last_name
@group = group
end

def ==(another)
self.instance_variables.all? do |v|
self.instance_variable_get(v) == another.instance_variable_get(v)
end
end
end

user1 = User.new("yamada", "taro", "A")
user2 = User.new("yamada", "taro", "A")
user3 = User.new("yamada", "taro", "B")

p user1 == user2 # => true
p user1 == user3 # => false