Skip to content

Instantly share code, notes, and snippets.

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 thomas-profitt/f0cdf5f60d11df4a6d32 to your computer and use it in GitHub Desktop.
Save thomas-profitt/f0cdf5f60d11df4a6d32 to your computer and use it in GitHub Desktop.
class Child
attr_accessor :age
def initialize(age: nil)
@age = age
end
end
class Mother
attr_accessor :child
def initialize(child: nil)
@child = child
end
end
class Father
attr_accessor :child
def initialize(child: nil)
@child = child
end
end
################################################################################
# margaret and ronald, which reference different Parent objects,
# both have @child properties that are references to the same Child object,
# also referenced by the susie variable.
susie = Child.new age: 8
margaret = Mother.new child: susie
ronald = Father.new child: susie
puts susie.age #=> 8
puts margaret.child.age #=> 8
puts ronald.child.age #=> 8
puts "Happy Birthday!"
susie.age = 9
puts susie.age #=> 9
puts margaret.child.age #=> 9
puts ronald.child.age #=> 9
# The Child object to which susie, margaret.child and ronald.child are
# references can be changed through any of the three references.
################################################################################
# timmy is a new reference to the same object susie references.
timmy = susie
susie.age = 10
puts susie.age #=> 10
puts timmy.age #=> 10
# This is an example of the same behavior, without other classes complicating it
################################################################################
# sarah is not a reference to the same object;
# sarah is a reference to an independent duplicate of the Child object susie
# references.
sarah = susie.dup
sarah.age = 11
puts susie.age #=> 10
puts sarah.age #=> 11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment