Skip to content

Instantly share code, notes, and snippets.

View nelantone's full-sized avatar

Tonio Serna nelantone

View GitHub Profile
# 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
a = ['a','b', 'c']
a.each do |b|
b.upcase!
a = ['reassign?']
end
p a # => ['reassign?'] yes! Reassignment
b = ['a','b', 'c']
b.each do |b|
b.upcase!
b = ['reassign?']
end
p b # => ['A','B','C'] nope! No reassignment
a = ['a','b', 'c']
a.each do |b|
b.upcase! # upcase is not an array method so we use `b` instead a[1] = 'd'
a[1] = 'd'
end
p a # => ['Ad','d','Cd']
@nelantone
nelantone / var_shadowing_collection explanation.md
Last active January 27, 2021 12:15
Explanation of variable shadowing in special case

on line 1 we initialize the variable assiging it to a string collection.

on line 4 we call each method on a object assigned to the object collection pointing to a.

on line 5 as we the variable is shadowing each specific objects 'a','b', 'c' will be modified to upcase(if we will try to call a.upcase! out of the block we will raise an exception).

on line 6 we modify again each object, but the array is the same, so we can't modify the array

on line 9 the return value is => ['Ad','Bd','Cd'] because we modify each object inside the collection but not the array the concept of variable shadowing is also applied in case will not be applied we will have a => ['A','d','C']

@nelantone
nelantone / var_shadowing_easy_example.rb
Created January 27, 2021 11:34
Easy example of variable shadowing in ruby collections
greet_var = "Hi there"
loop do |greet_var| # |greet_var| block parameter
greet_var = "What's up from the block" # inner scope `greet_var`
end
greet_var # => "Hi there" # the outer sope variable is protected
a = ['a','b', 'c']
a.each do |a|
a.upcase!
a[1] = 'd'
end
p a
str = "hello"
str.is_a?(Object)
str.class
class String
def star
self + " *"
end
end
@nelantone
nelantone / cat.rb
Last active July 26, 2016 14:07
3.4
class Cat
attr_reader :color, :breed
attr_accessor :name
def initialize(color, breed, hungry)
@color = color
@breed = breed
@hungry = true
end
def fav_foods
food_array = []
3.times do
puts 'please choose your favorite food'
food_array << gets.chomp
end
puts "Your favorite foods are #{food_array}.join(', ')."
p food_array