class Hello
@hello = \"hello\"
def display
puts @hello
end
end
h = Hello.new
h.display
I created the class above. It doesn\'t prin
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.