attr_reader explained

L

libsfan01

can someone explain how attr_reader works?

i can't find a good explanation anywhere.

please help!
 
T

Tim Becker

can someone explain how attr_reader works?

i can't find a good explanation anywhere.

please help!


It's built in to the language, so it 'works' by magic for all
practical purposes, it's implemented in `object.c` if you want to take
a look at the implementation. If you wanted to implement it in Ruby,
you do something like this:
def new_attr_reader cl, sym
str = "def #{sym.to_s}; @#{sym.to_s}; end"
cl.class_eval str
end
class Test; end
new_attr_reader Test, :my_new_reader
Test.new().my_new_reader

The built in `attr_reader` takes an array of sym's, but you get the idea.
-tim
 
R

Raj Sahae

libsfan01 said:
can someone explain how attr_reader works?

i can't find a good explanation anywhere.

please help!
attr_reader, in it's common usage, creates instance variables and
defines a method by which you can read them.

Class Test
def initialize(num)
@test=num
end

def test
@test
end
end

If you were to use attr_reader instead, your class definition would be

Class Test
attr_reader :test
def initialize(num)
@test = num
end
end
 
S

Stefano Crocco

Alle sabato 3 marzo 2007, Raj Sahae ha scritto:
attr_reader, in it's common usage, creates instance variables and
defines a method by which you can read them.

Actually, attr_reader doesn't create the variable, just the accessor method.
To see this, do the following in irb:
class C
attr_reader :var
def var_defined?
defined?(@var)
end
end => nil
c=C.new
=> # said:
c.var_defined? => nil
class C
def initialize
@var=nil
end
end => nil
c1=C.new
=> # said:
c1.var_defined?
=> "instance-variable"

As you can see, in the first case (the variable called c) doesn't have the
@var instance variable defined. Even after you call the var method defined
using attr_reader, the variable is still not defined. To define it, you need
to explicitly assign it to a value (using @var= something inside an instance
method of the class or using instance_variable_set)

Stefano
 
A

Austin Ziegler

It's built in to the language, so it 'works' by magic for all
practical purposes, it's implemented in `object.c` if you want to take
a look at the implementation. If you wanted to implement it in Ruby,
you do something like this:

Actually, that's not true. It's written in C, but that's not the same
as being built into the language. It's a method on Module, so it *can*
be overridden.
Making attribute readers for bar
Making attribute readers for baz, quux

-austin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,236
Messages
2,571,185
Members
47,820
Latest member
HortenseKo

Latest Threads

Top