Skip to content

Instantly share code, notes, and snippets.

@kkchu791
Last active November 7, 2015 06:51
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 kkchu791/80be51084315b7a7ebe3 to your computer and use it in GitHub Desktop.
Save kkchu791/80be51084315b7a7ebe3 to your computer and use it in GitHub Desktop.
# I think the problem lies in class Charlie not being able to inherit the instance variables from class Guitar.
#For example, when we run this code:
class Guitar
def initialize(brand, color)
@color = color
@brand = brand
end
end
class Charlie < Guitar
def initialize(brand)
@brand = brand
end
def play(arg)
"I'm playing my #@brand #@color guitar"
end
end
g = Guitar.new("Gibson", "Blue")
c = Charlie.new(g)
p c
p c.play(g)
#the output is :
#<Charlie:0x007fc78c9ee0c0 @brand=#<Guitar:0x007fc78c9ee0e8 @color="Blue", @brand="Gibson">>
#"I'm playing my #<Guitar:0x007fc78c9ee0e8> guitar"
#Class Charlie is not able to reach those instance variables because they are still bound to their instance of class Guitar.
#However, if we change the instance variables to class variables, then class Charlie would be able to access those variables.
class Guitar
def initialize(brand, color)
@@color = color
@@brand = brand
end
end
class Charlie < Guitar
def initialize(brand)
@brand = brand
end
def play(arg)
"I'm playing my #@@brand #@@color guitar"
end
end
g = Guitar.new("Gibson", "Blue")
c = Charlie.new(g)
p c
p c.play(g)
#Output:
#<Charlie:0x007f9a0b1f6650 @brand=#<Guitar:0x007f9a0b1f6678>>
# "I'm playing my Gibson Blue guitar"
# However, using class variables are frowned upon in Ruby.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment