2012-04-07 107 views
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) 

我想訪問保存變量getsaves 當我在類範圍之外,我該怎麼辦?:這個

puts saves variable that is inside getsaves 

回答

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