class Song
def name @name
end
def artist @artist
end
def duration @duration
end
end
Do I also have to declare @name, @artist, and @duration within the method? Or
are they implicitly declared by declaring the accessor methods?
What about this case?
class Song
attr_reader :name, :artist, :duration
end
In general, how do member variables work? Are they all private and require
accessor/reader methods to be accessed at all? My background includes a little
bit of C/C++ and Java.
class Song
def name; @name; end
def artist; @artist; end
def duration; @duration; end
end
Do I also have to declare @name, @artist, and @duration within the
method? Or are they implicitly declared by declaring the accessor
methods?
Ruby doesn’t have declarations. An instance variable (@name, etc.)
is created by use. Ruby will complain in a few situations if a
variable is used without first being assigned, but that mostly has
to do with local variables.
What about this case?
class Song
attr_reader :name, :artist, :duration
end
I tend to do this even at the beginning of my classes, even though
all it does is create readers. In most cases, your instance
variables will be created in the initializer of your class.
-austin
– Austin Ziegler, austin@halostatue.ca on 2002.11.15 at 17.16.33
class Song
attr_reader :name, :artist, :duration
end
expands to:
class Song
def name @name
end
def artist @artist
end
def duration @duration
end
end
Do I also have to declare @name, @artist, and @duration within the
method? Or are they implicitly declared by declaring the accessor
methods?
You don’t have to. Ruby use a first-use policy for variables. Meaning
it’s declared and defined when Ruby first encounter the variable. Or
if you like you can do: attr :name, :artist, :duration which will
simply declare them (mostly for documentation purposes).
In general, how do member variables work? Are they all private and
require accessor/reader methods to be accessed at all? My background
includes a little bit of C/C++ and Java.
They are all private to outsider (not subclasses). To make them
public, you have to either attr_reader or attr_writer or attr_accessor
them.
Expriment with irb. It’s the handiest tool to explore ruby.
In general, how do member variables work? Are they all private and
require accessor/reader methods to be accessed at all? My background
includes a little bit of C/C++ and Java.
They are all private to outsider (not subclasses). To make them
public, you have to either attr_reader or attr_writer or attr_accessor
them.
I think it’s worth clarifying here: member variables are always protected.
They are not “made public” by attr_* methods - because these create methods,
not tunnels-by-which-member-variables-can-be-accessed. It’s a subtle
difference … until someone redefines the ‘x=’ method.