0
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)

当我在类范围之外时,我想访问 saves 变量,getsaves 我该怎么做?:

puts saves variable that is inside getsaves
4

1 回答 1

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变量。

于 2012-04-07T15:09:41.467 回答