Skip to content

Instantly share code, notes, and snippets.

@eriktrautman
Created January 12, 2013 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eriktrautman/4520657 to your computer and use it in GitHub Desktop.
Save eriktrautman/4520657 to your computer and use it in GitHub Desktop.
Testing whether TestChild is going to be able to modify TestParent's string1 and array1, or, more generally, how to avoid dumb pass-by-reference errors.
# Testing whether TestChild is going to be able to modify TestParent's
# string1 and array1, or, overall, which objects are really pass-by-reference
# and which are not [in this case, testing strings and arrays]
class TestParent
attr_accessor :string1, :array1
def initialize(string1, array1)
@string1 = string1
@array1 = array1
puts
puts "The parent's starting string is: #{@string1}"
puts "The parent's starting array is: #{@array1.inspect}"
@t2 = TestChild.new(@string1, @array1, self)
end
end
class TestChild
def initialize(string, array, test_parent)
@string2 = string
@string2 << " dude!" # will this modify TestParent's string???
@array2 = array
@array2 << ["cookies", "are", "awesome"] # will this modify TestParent's array???
@test_parent = test_parent
# ... let's find out!
puts
puts "The parent's string is now: #{@test_parent.string1}"
puts "The child's string is now: #{@string2}"
puts
puts "The parent's array is now: #{@test_parent.array1.inspect}"
puts "The child's array is now: #{@array2}"
puts
end
end
t = TestParent.new("howdy", [1,2])
# RESULTS:
# YES! BOTH the parent's string1 AND array1 WERE modified when we
# used the shovel operator in the TestChild.
# What does this mean? BE CAREFUL how you treat the objects you pass around!
# If you use destructive operations on them (eg. the shovel <<), it WILL mess
# up the parent's objects as well.
# To fix this, you either need to use non-destructive operations OR pass in
# duplicates of the original objects instead of (references to) the real deal.
# In this case, if instead of @string2 << " dude!" we had used
# @string2 += " dude!" or instead of @array2 << [stuff], we had used
# @array2 += [stuff], we would have been fine. Lesson learned.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment