Tim Hunter
12/29/2006 12:48:00 PM
Krekna Mektek wrote:
> Hi list, I've got this probably lame questions.
>
> In the Pickaxe book 2nd ed. they talk about the attr_reader and
> attr_writer on pages 28 and 29 of the book.
>
> There are these attr_reader (eh, methods?) things, which use symbols
> instead of variables, why does Ruby use symbols here, what would be
> the problem if one uses the variable names instead? The symbol is
> pointing to the variable, but the variable is the handle on the data
> (variable value) anyway. Like a symlink pointing to a symlink pointing
> to the actual file.
>
attr_reader and its friends are methods in the Module class. The symbols
are arguments to the method that specify the names of the reader methods
to be defined. You could certainly use a variable in the argument list,
just like you can for any other method call, but in that case
attr_reader would use the value of the variable as the method name, not
the variable name itself. That is,
foo = "xxx"
attr_reader foo
defines the "xxx" method, not the "foo" method. Of course this may be
exactly what you want to happen. It's a common technique in Ruby
metaprogramming.
> And on page 44 (Containers, Implementing a SongList container)
>
> class SongList
> def [](index)
> @songs[index]
> end
> end
>
> Why is there this [] method in the class SongList, when one is able to
> use the [] method on the songs array anyway? Is this because of the
> church of good design, that one must access or change the @songs array
> via accessor methods, instead of changing the array directly?
You can't access @songs outside of the method definition itself, so if
you want to provide a way of indexing it to the users of the class you
must provide a method such as this one.
>
> Krekna
>