Understanding Object Assignment in Ruby: Duplicates and References Explained
This guide explores the intricacies of object assignment in Ruby, focusing on how assigning one object to another can lead to unexpected results—specifically the concept of object references versus object duplication. We demonstrate how changing a value in one object can affect another when they reference the same object, emphasizing the importance of understanding variable assignments, object IDs, and the implications of mutability in Ruby programming. Ideal for Ruby developers aiming to deepen their understanding of object-oriented concepts.
Understanding Object Assignment in Ruby: Duplicates and References Explained
E N D
Presentation Transcript
Object CreationCAVEAT EMPTOR!!! Addendum to unit 8 Gideon Frieder 2012
irb(main):001:0> a = 5 => 5 irb(main):002:0> a.object_id => 11 irb(main):003:0> b = 6 => 6 irb(main):004:0> b.object_id => 13 irb(main):005:0> b = a => 5 irb(main):006:0> b.object_id => 11
irb(main):001:0> a = [1,2,3] => [1, 2, 3] irb(main):002:0> a.object_id =>15627456 irb(main):003:0> b = a => [1, 2, 3] irb(main):004:0> b.object_id =>15627456 irb(main):005:0> a => [1, 2, 3] irb(main):006:0> b => [1, 2, 3]
Now see this……. irb(main):007:0> a[1] = 99 => 99 PART of a is changed irb(main):008:0> a => [1, 99, 3] What about b? irb(main):009:0> b => [1, 99, 3]
irb(main):001:0> a = [1,2,3] => [1, 2, 3] irb(main):002:0> b = Array.new => [] irb(main):003:0> a.object_id =>16770948 irb(main):004:0> b.object_id =>16263168 irb(main):005:0> b = a => [1, 2, 3] irb(main):006:0> b.object_id =>16770948 irb(main):007:0> a[1] = 99 => 99 irb(main):008:0> a => [1, 99, 3] irb(main):009:0> b => [1, 99, 3]
irb(main):001:0> a = [1,2,3] => [1, 2, 3] irb(main):002:0> b = Array.new(a) =>[1, 2, 3] irb(main):003:0> a.object_id => 16007148 irb(main):004:0> b.object_id => 16833036 irb(main):005:0> a[1] = 99 => 99 irb(main):006:0> a => [1, 99, 3] irb(main):006:0> b => [1, 2, 3]
New value assignment creates new object Assigning of an existing object name to another name does NOT create a new object, It creates a duplicate name for the same object