请原谅newbiew的总问题,但为什么@game_score总是为零呢?
#bowling.rb
class Bowling
  @game_score = 0
    def hit(pins)
        @game_score = @game_score + pins
    end
    def score
        @game_score
    end
end
Run Code Online (Sandbox Code Playgroud) 我的印象是Ruby中的类定义可以重新打开:
class C
  def x
    puts 'x'
  end
end
class C
  def y
    puts 'y'
  end
end
Run Code Online (Sandbox Code Playgroud)
这按预期工作,并y添加到原始类定义中.
我很困惑为什么以下代码不能按预期工作:
class D
  x = 12
end
class D
  puts x
end
Run Code Online (Sandbox Code Playgroud)
这将导致NameError异常.为什么在重新打开课程时会启动新的本地范围?这似乎有点违反直觉.在扩展课程时,有没有办法继续以前的本地范围?