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
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

@@gibble = ‘FOOgibble’
def self.gibble

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

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

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

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

f1,f2 =,
b1,b2 =,
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’”

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs