Ruby初学者。实例变量未显示

时间:2016-06-01 06:22:58

标签: ruby class variables instance

var Client_ID = xmlDoc.getElementsByTagName('Client_ID')[0].childNodes[0]

当我在Terminal中运行上面的代码时,它显示为:

class Player
  def initialize (name, age, start_year)
    @name       = name.capitalize
    @age        = age
    @start_year = start_year
  end

  def playing_for
    current_year  = Time.new.strftime("%Y")
    num_of_years  = current_year - @start_year
    @num_of_years = num_of_years
  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

jon = Player.new("jon", 41, 2009)
puts jon

并且不显示Hi my name is Jon. I am 41 years old. I have been playing Ultimate for years.

显然,我定义#{@num_of_years}的方式有问题,但我无法弄清楚是什么。

1 个答案:

答案 0 :(得分:3)

@num_of_years不打印,因为变量未设置(未初始化的实例变量的值为nil,而"#{nil}"的结果为空字符串。)

@name@age@start_year都设置在initialize中,通过调用Player.new来调用,to_sputs调用{1}}:

jon = Player.new("jon", 41, 2009) # <- "new" calls Player#initialize
puts jon                          # <- "puts" calls Player#to_s
另一方面,

@num_of_years设置在永远不会调用的playing_for中(这就是Wand Maker wanted to say)。

您可以在致电puts之前手动调用该方法:(记得通过将strftime("%Y")替换为year来修复the bug

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

打印:

Hi, my name is Jon. I am 41 years old. I have been playing Ultimate for 7 years.

但是记住每次调用这个方法都会很快变得单调乏味。

在初始化中设置@num_of_years更容易,就像其他实例变量一样:

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.

或者您可以定义一种计算差异的方法。但在这种情况下,您不需要另一个实例变量,只需返回值:

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.

查看to_s方法。我已将#{@num_of_years}替换为#{playing_for}