Reputation: 2467
I have the following code that creates a viking game character and gives them random stats such as health, age and strength.
class Viking
def initialize(name, health, age, strength)
@name = name
@health = health
@age = age
@strength = strength
end
def self.create_warrior(name)
age = rand * 20 + 15
health = [age * 5, 120].min
strength = [age/2, 10].min
Viking.new(name, health, age, strength)
end
end
brad = Viking.create_warrior("Brad")
puts "New Warrior Created!"
The create_warrior function returns all those values, but how do I access them so I could see the stats.
For example this doesn't work but I would like to see the age or health of the new Viking brad (i.e brad.age
even though that wouldn't work because it's not a method).
So how do I access those variables (without making them global).
Upvotes: 0
Views: 57
Reputation: 1156
Use the attr_reader
method, it creates a attribute method to point to the variable in the initialize
method which is private. Its read-only
You can use attr_writer
to write only
And attr_accessor
to both read and write
class Viking
attr_reader :age, :name, :health, :strength
def initialize(name, health, age, strength)
@name = name
@health = health
@age = age
@strength = strength
end
def self.create_warrior(name)
age = rand * 20 + 15
health = [age * 5, 120].min
strength = [age/2, 10].min
Viking.new(name, health, age, strength)
end
end
brad = Viking.create_warrior("Brad")
puts "New Warrior Created!"
Upvotes: 0
Reputation: 752
If you really don't want them global, try instance_variable_get
method http://apidock.com/ruby/Object/instance_variable_get
puts brad.instance_variable_get(:@age)
Upvotes: 1
Reputation: 4986
Use attr_accessor :name, :health, :age, :strength
if you would like the variables to be both readable and writable or attr_reader :name, :health, :age, :strength
if you would like them to be read only.
After this you can access with brad.varname
e.g. brad.name
etc...
Upvotes: 3
Reputation: 11689
Use attr_reader :age
, so you can simply use brad.age
, same goes for the other variables
Upvotes: 1