Skip to content

Instantly share code, notes, and snippets.

@ArturT
Created February 15, 2018 11:42
Show Gist options
  • Save ArturT/588e2588431c56fc093f5aa1c1e003b3 to your computer and use it in GitHub Desktop.
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
# 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