On Sat, Feb 22, 2003 at 09:38:17PM +0900, Brian Candler wrote:
> Here's another one while we're on the subject of "consistent and
> predictable" :-)
> 
>   class Tree
>     @count = 0
>     @@count = 50
>     def Tree.inc
>       @count += 1
>     end
>     def Tree.inc2
>       @@count += 1
>     end
>   end
> 
>   def Tree.dec
>     @count -= 1
>   end
>   def Tree.dec2
>     @@count -= 1
>   end
> 
>   puts Tree.inc    #>> 1
>   puts Tree.inc2   #>> 51
>   puts Tree.dec    #>> 0
>   puts Tree.dec2   #>> uninitialized class variable @@count in Object (NameError)
> 
> (but in this case it's class variables, not class instance variables, which
> appear to be behaving inconsistently)

The class whose variable will be used is selected at compile time.
IMHO this is evil as it is a closure-like mechanism --- on a class method
level --- not available when using locals.

It is at least evil enough to deserve a warning :)

batsman@tux-chan:/tmp$ expand -t 2 l.rb
class Tree
  @@count = "Tree's @@count"
  def Tree.dec
    p @@count.id, @@count
  end
end

@@count = "Top level's"
class << self
  @@count = "Top level's (2)"
  # it's the same class variable.
end

def Tree.dec2
  p @@count.id, @@count
  # refers to the class variable of the top-level object's class
  # not that of Tree
end

class << Tree
  def dec3
    p @@count.id, @@count
  end
end

class Tree
  class << self
    def dec4
      p @@count.id, @@count
    end
  end
end

class SubTree < Tree
  def SubTree.inc
    p @@count.id, @@count
  end
end

p self.class
Tree.dec
Tree.dec2
Tree.dec3
Tree.dec4
SubTree.inc
batsman@tux-chan:/tmp$ ruby l.rb
l.rb:10: warning: class variable access from toplevel singleton method
Object
538045926
"Tree's @@count"
538045876
"Top level's (2)"
l.rb:22: warning: class variable access from toplevel singleton method
l.rb:22: warning: class variable access from toplevel singleton method
538045876
"Top level's (2)"
538045926
"Tree's @@count"
538045926
"Tree's @@count"

-- 
 _           _                             
| |__   __ _| |_ ___ _ __ ___   __ _ _ __  
| '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \ 
| |_) | (_| | |_\__ \ | | | | | (_| | | | |
|_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_|
	Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

> Tut mir Leid, Jost, aber Du bist ein unertraeglicher Troll.
Was soll das? Du *beleidigst* die Trolle!
	-- de.comp.os.unix.linux.misc