@num_of_years ist not printed, because the variable wasn't set (uninitialized instance variables have a value of nil and "#{nil}" results in an empty string).
@name, @age and @start_year are all set in initialize which is invoked by calling Player.new, and to_s is invoked by puts:
jon = Player.new("jon", 41, 2009) # <- "new" calls Player#initialize
puts jon # <- "puts" calls Player#to_s
@num_of_years on the other hand is set in playing_for which is never called (this is what Wand Maker wanted to say).
You could call the method manually before calling puts: (remember to fix the bug by replacing strftime("%Y") with year)
jon = Player.new("jon", 41, 2009)
#=> #<Player:0x007fab8a8aa448 @name="Jon", @age=41, @start_year=2009>
jon.to_s
#=> "Hi, my name is Jon. I am 41 years old. I have been playing Ultimate for years."
jon.playing_for
#=> 7
jon.to_s
#=> "Hi, my name is Jon. I am 41 years old. I have been playing Ultimate for 7 years."
puts jon
Prints:
Hi, my name is Jon. I am 41 years old. I have been playing Ultimate for 7 years.
But remembering to call the method every time becomes tedious very quickly.
It's easier to set @num_of_years in initialize, just like the other instance variables:
class Player
def initialize (name, age, start_year)
@name = name.capitalize
@age = age
@start_year = start_year
@num_of_years = Time.new.year - start_year
end
def to_s
"Hi, my name is #{@name}. I am #{@age} years old. I have been playing Ultimate for #{@num_of_years} years."
end
end
puts Player.new("jon", 41, 2009)
#=> Hi, my name is Jon. I am 41 years old. I have been playing Ultimate for 7 years.
Or you could define a method to calculate the difference. But you don't need another instance variable in this case, just return the value:
class Player
def initialize (name, age, start_year)
@name = name.capitalize
@age = age
@start_year = start_year
end
def playing_for
Time.new.year - @start_year
end
def to_s
"Hi, my name is #{@name}. I am #{@age} years old. I have been playing Ultimate for #{playing_for} years."
end
end
puts Player.new("jon", 41, 2009)
#=> Hi, my name is Jon. I am 41 years old. I have been playing Ultimate for 7 years.
Take a look at the to_s method. I've replaced #{@num_of_years} with #{playing_for}.
playing_forthat sets value for@num_of_years?Time.new.strftime("%Y")returns a string, socurrent_year - @start_yearbecomes"2016" - 2009which doesn't work (you can't subtract a number from a string). UseTime.new.yearinstead.