如何访问此变量?

时间:2012-04-07 15:05:19

标签: ruby scope

class Player
  def getsaves
    print "Saves: "
    saves = gets
  end
  def initialize(saves, era, holds, strikeouts, whip)
  end
end

我有上面的代码......让我说然后写。

j = Player.new(30, 30, 30, 30, 30)

我想访问getsaves中的保存变量 当我在课堂范围之外时,我该怎么做?:

puts saves variable that is inside getsaves

1 个答案:

答案 0 :(得分:2)

正如您所编写的那样,saves变量不仅无法从类范围外部访问,而且超出了getsaves方法末尾的范围

你应该做这样的事情:

class Player
  def getsaves
    print "Saves: "
    @saves = gets # use an instance variable to store the value
  end
  attr_reader :saves # allow external access to the @saves variable
  def initialize(saves, era, holds, strikeouts, whip)
  end
end

现在,您只需使用j.saves即可访问@saves变量。