Array with contents class object is set differently by mom of class object

Asked 2 years ago, Updated 2 years ago, 32 views

There are two arrays of class objects with the following contents, and I would like to take a set of differences.

foo_people
#=>[#<Person:0x007fd36402cee0>@name="ichiro",#<Person:0x007fd36484c940>@name="jiro",#<Person:0x007fd364 aac118>@name="saburo" ]
bar_people
#=>[#<Person:0x007fd364a6f3a8>@name="ichiro",#<Person:0x007fd364a36170>@name="jiro" ]

The image looks like the one below, but I am having trouble getting the difference because the object_id is different.

foo_people-bar_people
#=>[#<Person:0x007fd364aac118>@name="saburo"]

ruby

2022-09-30 14:28

1 Answers

Nice to meet you. Array#- uses Object#eql? to compare items. You must define the eql? method in the Person class to ensure identity.
Also, remember to define the hash method if you define the eql? method.

In this example, in the Person class (assuming there are only members named @name,

defeql?(other)
    other.name==@name
end

def hash
    @name.hash
end

If the object IDs are different but the contents are the same, an array difference will be created.

If you have other members besides @name, define hash a little smarter.(Returns hash values of the combined string with all members as strings...)


2022-09-30 14:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.