On 4/7/06, Nathan Olberding <nathan.olberding / gmail.com> wrote:> zdennis wrote:[...]> It's not so much that I feel strongly as much as that it perplexes me.> I guess I just wanted to make sure my meds haven't been replaced with> crazy pills.>> I thought of this, too: isn't it odd that you can define class> variables in a definition of how instances of a class should work, but> you can't define their accessors? It seems inconsistent. If it's> agreed that this is inconsistent, I'll post something to the site you> mentioned, but if it's that way for a reason, I'll just take your much> appreciated advice, learn that much more, and be that much less of a> newbie.
I'm not sure you're clear on the concept (I don't mean that meanly).
Consider:
class Foo @bar = 5 # the instance variable @bar of <Foo:class> (1) @@bar = 5 # the class variable @bar of <Foo:class> (2)
def initialize @bar = 5 # the instance variable @bar of a Foo instance. (3) end end
When you do:
class Foo class << self attr_accessor :bar end end
You are accessing (1). (2) is not affected.
I addressed some of the reasons *why* you wouldn't simply do:
attr_accessor :@var
in my article on Symbols in January (on the O'Reilly Ruby blog), butremember that attr_accessor defines methods. There's no differencebetween the types of code here. In fact, if you run "ruby -w" on thiscode, you'll get warnings about method redefinitions for the latter two.
class Foo attr_accessor :bar
def bar; @bar; end def bar=(x); @bar = x; end end
Jumping back to the Pickaxe:
class Song attr_accessor :duration # in seconds
def minutes=(x); @duration = (x * 60).to_i; end def minutes; @duration / 60; end end
s = Song.new s.duration = 60 s.minutes # => 1 s.minutes = 2.3 s.duration # => 138
For documentation purposes, I'll sometimes do the following:
class Song # The duration of the song in seconds. attr_accessor :seconds # The duration of the song in minutes. attr_accessor :minutes remove_method :minutes, :minutes= def minutes=(m) # :nodoc: @seconds = (x * 60).to_i end def minutes # :nodoc: @duration / 60 end end
So using attr_accessor doesn't declare a variable; it declares a pair ofmethods that access and may instantiate a variable, but doesn't have to.And *that* is why doing "attr_accessor :@var" really wouldn't beappropriate.
-austin--Austin Ziegler * halostatue / gmail.com * Alternate: austin / halostatue.ca