I created a class that generates a different name for each instance, but a test fails unexpectedly when instantiating two instances in one statement.
Here is the class.
class Robot
attr_accessor :name
@@current_name = 'AA000'
def initialize
@name = @@current_name
@@current_name.next!
end
end
Here the class behaves as expected
irb(main):009:0> Robot.new.name
=> "AA001"
irb(main):010:0> Robot.new.name
=> "AA002"
Here is the unexpected behavior, I was expecting false. This code is in a test on an exercise I am trying to get passing, so I can't change the test.
irb(main):011:0> Robot.new.name == Robot.new.name
=> true
Checking the object_id reveals that two different instances are being created.
irb(main):012:0> Robot.new.object_id == Robot.new.object_id
=> false
Why is Ruby doing this, what should I do to fix it & assuming there is a term for this, what could I have typed into search to find answered questions about this.
Aucun commentaire:
Enregistrer un commentaire