How can I access the name variable in the game class, when I assign it in the Player Class? I am slightly confused about classes inheritance and scope. (Ruby)
class Game
attr_accessor :name
def display_name
puts "Name is #{@@name}"
end
end
class Player
attr_accessor :name
def get_name
puts "What is your name? "
@@name = gets.chomp
end
end
player = Player.new()
player.get_name
game = Game.new()
game.display_name()
Thanks
CodePudding user response:
Player
and Game
are two different classes and not connected to each other. And two different instance also know nothing about each other in your example.
If you want to read an instance's variable from another instance then you need to pass the first instance to the other one to have a reference to it and be able to call a method on it.
In the context of your example with a Game
and a Player
that might look like the following (there are other way possible).
For example like this:
class Game
def initialize(player) # allows to pass a player when a game is created
@player = player # assigns the player to a variable for later use
end
def display_name
puts "Name is #{@player.name}" # call `name` on the stored variable
end
end
class Player
attr_reader :name
def get_name
puts "What is your name? "
@name = gets.chomp
end
end
player = Player.new
player.get_name
#=> What is your name?
#=> Peter Parker
game = Game.new(player)
game.display_name
#=> Name is Peter Parker
Please also note that instance variables in Ruby have only one @
at the beginning.
CodePudding user response:
@@name
should be changed to @name
because
@@
sets a class variable@
sets an instance variable
and attr_accessor
only works with instance variables
instance variables are 'linked' to their object
class Player
attr_accessor :name
end
a = Player.new # create first object
b = Player.new # create second object
a.name = "Gwen"
b.name = "Toph"
puts a.name
# => Gwen
puts b.name
# => Toph
to access instance variables of an object, you can pass the object into your method
class Game
def display_name(player)
puts "Name is #{player.name}"
end
end
game = Game.new
game.display_name(a)
# => Name is Gwen
game.display_name(b)
# => Name is Toph