7
7stud 7stud
On p. 30-31 of "Programming Ruby (2nd ed)", there is this example:
class Song
attr_reader :name, :artist, :duration
end
and the text says:
"The corresponding instance variables, @name, @artist, and @duration,
will be created for you."
But I discovered that I still have to define an initialize method to
create objects:
class Song
attr_reader :x, :y, :z
def initialize(x, y, z)
@x = x
@y = y
@z = z
end
end
s = Song.new(10, 20, 30)
puts s.x
So, it seems like initialize is what creates the instance variables.
Or, does attr_reader somehow do its thing before initialize is called?
If so, why is it considered important to know that attr_reader creates
the instance variables instead of initialize?
class Song
attr_reader :name, :artist, :duration
end
and the text says:
"The corresponding instance variables, @name, @artist, and @duration,
will be created for you."
But I discovered that I still have to define an initialize method to
create objects:
class Song
attr_reader :x, :y, :z
def initialize(x, y, z)
@x = x
@y = y
@z = z
end
end
s = Song.new(10, 20, 30)
puts s.x
So, it seems like initialize is what creates the instance variables.
Or, does attr_reader somehow do its thing before initialize is called?
If so, why is it considered important to know that attr_reader creates
the instance variables instead of initialize?