Re: metaprogramming surprise?

From: Garance A Drosehn [mailto:[email protected]]

Any chance that class variables will disappear in Ruby 2.0?
I’m only half joking.

I use them fairly frequently, and have never been tripped up by them.
They seem like a pretty straightforward idea to me. I tend to use
them
for “config-ish” things in the class, which would need to
have the same value in all instances of the class.

Do you rely on the fact that subclasses will share the same
variables/values? Or do you rarely subclass class that you’re using
class variables on?

Out of curiosity, why do you think that you use them instead of class
instance variables? Because they’re slightly more convenient to access
from the instance?

class Foo
@whee = ‘FOOwhee’
class << self
attr_reader :whee
end

@@gibble = ‘FOOgibble’
def self.gibble
@@gibble
end

def stuff
“#{self.class} ##{object_id} says whee is ‘#{self.class.whee}’” +
" and gibble is ‘#@@gibble’"
end
end

class Bar < Foo
@whee = ‘BARwhee’
@@gibble = ‘BARgibble’
end

p Foo.whee, Bar.whee
#=> “FOOwhee”
#=> “BARwhee”

p Foo.gibble, Bar.gibble
#=> “BARgibble”
#=> “BARgibble”

f1,f2 = Foo.new, Foo.new
b1,b2 = Bar.new, Bar.new
p f1.stuff, f2.stuff, b1.stuff, b2.stuff
#=> “Foo #21076010 says whee is ‘FOOwhee’ and gibble is ‘BARgibble’”
#=> “Foo #21075960 says whee is ‘FOOwhee’ and gibble is ‘BARgibble’”
#=> “Bar #21075920 says whee is ‘BARwhee’ and gibble is ‘BARgibble’”
#=> “Bar #21075910 says whee is ‘BARwhee’ and gibble is ‘BARgibble’”