Total newbie: Instance variables in ruby?

后端 未结 4 1347
旧巷少年郎
旧巷少年郎 2020-12-01 11:39

Pardon the total newbiew question but why is @game_score always nil?

#bowling.rb

class Bowling
  @game_score = 0
    def hit(pins)
        @game_score = @ga         


        
4条回答
  •  忘掉有多难
    2020-12-01 11:51

    Because you don't have

    def initialize
      @game_score = 0
    end
    

    The assignment in the class definition is not doing what you think it is doing, and when hit gets invoked it can't add to nil.

    If you now ask what happened to @game_score?, well, always remember Class is an object and Object is a class.

    It's way cool the way Ruby classes have this Zen-like "real" existence. Ruby doesn't precisely have named classes, rather, class names are references to objects of class Class. By assigning to @game_score outside of an instance method you created a class instance variable, an attribute of the class object Bowling, which is an instance of class Class. These objects are not, in general, very useful. (See Chapter 1, The Ruby Way, Hal Fulton.)

提交回复
热议问题