LoginSignup
4
4

More than 5 years have passed since last update.

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

Posted at
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
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4