本文介绍了我如何访问这个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Player
def getsaves
print "Saves: "
saves = gets
end
def initialize(saves, era, holds, strikeouts, whip)
end
end
我有上面的代码...可以说我然后写.
I have the code above...lets say I then write.
j = Player.new(30, 30, 30, 30, 30)
我想访问 getsaves
中的 saves 变量当我在课堂范围之外时,我该怎么做?:
I want to access the saves variable in getsaves
When I am outside the class scope, how do I do this?:
puts saves variable that is inside getsaves
推荐答案
正如您所写,saves
变量不仅不能从类作用域外访问,而且超出了作用域在 getsaves
方法的末尾.
As you've written it, not only is the saves
variable inaccessible from outside the class scope, it goes out of scope at the end of the getsaves
method.
你应该这样做:
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
变量.
Now you can simply use j.saves
to access the @saves
variable.
这篇关于我如何访问这个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!