Last active
January 27, 2021 23:17
-
-
Save nelantone/354fcf0016f16a20d74b166041256cb7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# Example 1 | |
# to see the object ids when we have a variable shadowing | |
a = [1, 2, 3] | |
a.object_id # => 1960 | |
a.map! do |a| | |
p a.object_id | |
a + 1 | |
end # 3 | |
# 5 | |
# 7 | |
# 3,5,7 are the object ids of 1,2 and 3 | |
a => [2, 3, 4] # we reassing each object with the +1 operation | |
a.object_id # => 1960 | |
# As we can see we have the same array because have the same object id | |
# Example 2 | |
# object_id when there is no variable shadowing | |
a = [1, 2, 3] | |
b = [4, 5, 6] | |
a.object_id # => 1960 | |
b.object_id # => 1980 | |
a.map! do |c| | |
p b.object_id | |
c + 1 | |
end # 1980 | |
# 1980 | |
# 1980 | |
# the object_id 1980 is from returning 3 times `b` as the object array | |
a => [2, 3, 4] # we also reassing each object with the +1 operation | |
a.object_id # => 1960 | |
b.object_id # => 1980 | |
# Example 3 | |
# object_id with a mix of variable shadowing `b` & reassigment inside the block on `c` | |
a = ['a', 'b', 'c'] | |
b = ['e', 'f', 'g'] | |
c = ['x'] | |
a.object_id # => 1820 | |
b.object_id # => 1840 | |
c.object_id # => 1850 | |
a.each do|b| # as `b` is defined outside the scope `|b|`is shadowing this variable. | |
p b # `b` value is shadowing with `b` local variable, then we will have instead each object id of `a` array | |
p a # `a` value is the array itself ['a', 'b', 'c'] | |
c = ['h', 'i', 'j'] # as `a`, `c` is not shadowing and we can easily reassign it inside the block | |
b = 'shadowing!' # local variable `b` is protected. We can't reassign `b` as `c`, ruby scopes this `b` shadowing in the block | |
end # "a" | |
# ["a", "b", "c"] | |
# "b" | |
# ["a", "b", "c"] | |
# "c" | |
# ["a", "b", "c"] | |
a # => ['a', 'b', 'c'] | |
b # => ['e', 'f', 'g'] | |
c # => ['h', 'i', 'j'] # as we can see, we re-wrote `c` | |
a.object_id # => 1820 | |
b.object_id # => 1840 | |
c.object_id # => 1880 # objet_id after `c` reassignment passed from `1850` to `1880`. It's another object! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment