When do Ruby instance variables get set?

前端 未结 6 1688
盖世英雄少女心
盖世英雄少女心 2020-12-02 04:42
class Hello
@hello = \"hello\"
    def display
        puts @hello
    end
end

h = Hello.new
h.display

I created the class above. It doesn\'t prin

6条回答
  •  天涯浪人
    2020-12-02 05:38

    there is a clear description in the book "The ruby programming language", read it will be very helpful. I paste it here(from chapter 7.1.16):

    An instance variable used inside a class definition but outside an instance method definition is a class instance variable.

    class Point
        # Initialize our class instance variables in the class definition itself
        @n = 0              # How many points have been created
        @totalX = 0         # The sum of all X coordinates
        @totalY = 0         # The sum of all Y coordinates
    
        def initialize(x,y) # Initialize method 
          @x,@y = x, y      # Sets initial values for instance variables
        end
    
        def self.new(x,y)   # Class method to create new Point objects
          # Use the class instance variables in this class method to collect data
          @n += 1           # Keep track of how many Points have been created
          @totalX += x      # Add these coordinates to the totals
          @totalY += y
    
          super             # Invoke the real definition of new to create a Point
                        # More about super later in the chapter
        end
    
        # A class method to report the data we collected
        def self.report
            # Here we use the class instance variables in a class method
            puts "Number of points created: #@n"
            puts "Average X coordinate: #{@totalX.to_f/@n}"
            puts "Average Y coordinate: #{@totalY.to_f/@n}"
        end
    end
    

    ......

    Because class instance variables are just instance variables of class objects, we can use attr, attr_reader, and attr_accessor to create accessor methods for them.

    class << self
      attr_accessor :n, :totalX, :totalY
    end
    

    With these accessors defined, we can refer to our raw data as Point.n, Point.totalX, and Point.totalY.

提交回复
热议问题