Created
February 15, 2018 11:42
-
-
Save ArturT/588e2588431c56fc093f5aa1c1e003b3 to your computer and use it in GitHub Desktop.
Using `+=` will create a local copy of variable instead of updating the reference
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 | |
errors = [] | |
def add_error_1(errors, arr) | |
errors += arr # this won't change the errors outside, instead of copy of errors will be created locally | |
puts "inside of func: #{errors.inspect}" | |
end | |
add_error_1(errors, ['an error 1']) # inside of func: ["an error 1"] | |
puts "outside: #{errors.inspect}" # outside: [] | |
# Example 2 | |
errors = [] | |
def add_error_2(errors, arr) | |
arr.each do |e| | |
errors << e # this changes errors outside | |
end | |
puts "inside of func: #{errors.inspect}" | |
end | |
add_error_2(errors, ['an error 2']) # inside of func: ["an error 2"] | |
puts "outside: #{errors.inspect}" # outside: ["an error 2"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment