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