Bill Kelly
12/28/2005 8:27:00 PM
From: "Steve Litt" <slitt@earthlink.net>
>
> I still don't understand why it's
>
> attr_reader :fname, :lname
>
> instead of
>
> attr_reader @fname, @lname
>
> How does attr_reader know that :fname corresponds to @fname. Seems like magic
> to me.
If this helps, attr_reader itself isn't magic or special Ruby syntax,
it's just a method that defines helper-methods for you, using whatever
names you provide it. The symbols :fname, :lname above are just
interpreted by attr_reader as names of methods we are asking it to
define, and names of corresponding instance variables we want it to
access. (Note that: attr_reader "fname", "lname" also works - it's
less convenient to type than the symbol equivalents.)
I think there are more elegant ways to do this, but here's one way we
could define our own attr_reader:
def my_attr_reader(*list_of_attr_names)
list_of_attr_names.each do |name|
eval <<-ENDFUNC
def #{name}
@#{name}
end
ENDFUNC
end
end
class Foo
my_attr_reader :foo, :bar
def initialize
@foo = 123
@bar = 456
end
end
f = Foo.new
puts f.foo, f.bar
# the above program outputs:
123
456
So you can see my_attr_reader is just taking a list of "names",
which we conveniently specify as symbols (but we could also
specify as strings, if we wanted.) Then my_attr_reader just
proceeds to use eval to define methods with the requested name,
accessing the corresponding instance variable. (Again, there
are probably more elegant ways to do this than using eval; it's
just one way.)
Hope this helps,
Regards,
Bill