L
libsfan01
can someone explain how attr_reader works?
i can't find a good explanation anywhere.
please help!
i can't find a good explanation anywhere.
please help!
can someone explain how attr_reader works?
i can't find a good explanation anywhere.
please help!
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
attr_reader, in it's common usage, creates instance variables andlibsfan01 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 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
=> "instance-variable"=> # said:c1.var_defined?
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.
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.