What have you found for these years?

2007-07-06

[Ruby] @v ? @@v ?


class C
attr_reader :v, :w
@v = 5
@@v = 10
def initialize
@w = 15
@@w = 20
end
end

eval('@v', C.send(:binding)) # -> 5
eval('@@v', C.send(:binding)) # -> undefined

eval('@w', C.new.send(:binding)) # -> 15
eval('@@w', C.new.send(:binding)) # -> undefined

eval('@v', Class.send(:binding)) # -> nil
eval('@@v', Class.send(:binding)) # -> undefined

Class.module_eval{attr_reader, :v, :w}
C.v # -> 5
C.w # -> nil
C.instance_eval{puts @v} # -> 5
C.instance_eval{puts @@v} # -> undefined
C.instance_eval{puts @w} # -> nil
C.instance_eval{puts @@w} # -> undefined
C.module_eval{puts @v} # -> 5
C.module_eval{puts @@v} # -> undefined
C.module_eval{puts @w} # -> nil
C.module_eval{puts @@w} # -> undefined

where are the class variables? @@

class C
def orz
puts [@@v, @@w].join(', ')
end
def self.xd
puts [@@v, @@w].join(', ')
end
end

C.new.orz # -> 10, 20
C.orz # -> 10, 20

eval('@@v', C.new.method(:orz).send(:binding)) # -> undefined
eval('@@v', C.method(:xd).send(:binding)) # -> undefined

class variable can only be bound in a real method?

0 retries:

Post a Comment

Note: Only a member of this blog may post a comment.



All texts are licensed under CC Attribution 3.0