Objects and Classes
Object Identity
Two objects can store equal values while still being separate object instances.
Object Identity
object_identity.rb
class Badge
attr_reader :name
def initialize(name)
@name = name
end
def ==(other)
other.is_a?(Badge) && name == other.name
end
end
other_name =
first = Badge.new("Ada")
second = Badge.new(other_name)
puts "first=#{first.name}"
puts "second=#{second.name}"
puts "same_object=#{first.equal?(second)}"
puts "same_value=#{first == second}"
class Badge
attr_reader :name
def initialize(name)
@name = name
end
def ==(other)
other.is_a?(Badge) && name == other.name
end
end
other_name =
first = Badge.new("Ada")
second = Badge.new(other_name)
puts "first=#{first.name}"
puts "second=#{second.name}"
puts "same_object=#{first.equal?(second)}"
puts "same_value=#{first == second}"
class Badge
attr_reader :name
def initialize(name)
@name = name
end
def ==(other)
other.is_a?(Badge) && name == other.name
end
end
other_name =
first = Badge.new("Ada")
second = Badge.new(other_name)
puts "first=#{first.name}"
puts "second=#{second.name}"
puts "same_object=#{first.equal?(second)}"
puts "same_value=#{first == second}"
object identity
`equal?` checks whether two variables point to the same object; `==` can compare object values.