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

Asked 1 months ago, Updated 1 months ago, 1 views

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

#=>[#<Person:0x007fd36402cee0>@name="ichiro",#<Person:0x007fd36484c940>@name="jiro",#<Person:0x007fd364 aac118>@name="saburo" ]
#=>[#<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.



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,

    [email protected]

def hash

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

© 2022 OneMinuteCode. All rights reserved.