How Do I Access This Variable?

2019-03-06 15:20发布

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)

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

标签: ruby scope
1条回答
叛逆
2楼-- · 2019-03-06 15:55

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.

You should do something like this instead:

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

Now you can simply use j.saves to access the @saves variable.

查看更多
登录 后发表回答