Created
September 18, 2013 05:09
-
-
Save jhamon/6604804 to your computer and use it in GitHub Desktop.
W1D2 - References, object_id, and mutability
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Be careful when referencing mutable objects | |
a = {} # => {} | |
b = a # => {} | |
a.object_id # => 70132601471180 | |
b.object_id # => 70132601471180 | |
a[:foo] = 'bar' # => "bar" | |
b # => {:foo=>"bar"} # Woah! | |
## Fixnums are a special case, because numbers are immutable. | |
x = 2 # => 2 | |
y = x # => 2 | |
x.object_id # => 5 | |
y.object_id # => 5 # Both x and y are referencing | |
# the same Fixnum object | |
x += 1 # => 3 | |
x.object_id # => 7 # The x reference now points to a different object. | |
y.object_id # => 5 # y still referencing the value 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment