J
James Edward Gray II
I was playing around with an idea in another thread and ran into a
surprise. Can anyone explain the following to me?
irb(main):015:0> class Module
irb(main):016:1> def cattr_accessor( *symbols )
irb(main):017:2> symbols.each do |sym|
irb(main):018:3* eval "def self.#{sym}( ) @@#{sym} end
irb(main):019:3" def self.#{sym}=( value ) @@#{sym} =
value end"
irb(main):020:3> end
irb(main):021:2> end
irb(main):022:1> end
=> nil
irb(main):023:0> class Accessor
irb(main):024:1> cattr_accessor ne, :two
irb(main):025:1> def self.fetch_one( )
irb(main):026:2> @@one
irb(main):027:2> end
irb(main):028:1> end
=> nil
irb(main):029:0> Accessor.one = "James"
=> "James"
irb(main):030:0> Accessor.two = "Gray"
=> "Gray"
irb(main):031:0> Accessor.one
=> "James"
irb(main):032:0> Accessor.two
=> "Gray"
irb(main):033:0> Accessor.fetch_one
NameError: uninitialized class variable @@one in Accessor
from (irb):26:in `fetch_one'
from (irb):33
from (null):0
Everything works as expected, save fetch_one(). Why does it not return
"James"?
Thanks.
James Edward Gray II
surprise. Can anyone explain the following to me?
irb(main):015:0> class Module
irb(main):016:1> def cattr_accessor( *symbols )
irb(main):017:2> symbols.each do |sym|
irb(main):018:3* eval "def self.#{sym}( ) @@#{sym} end
irb(main):019:3" def self.#{sym}=( value ) @@#{sym} =
value end"
irb(main):020:3> end
irb(main):021:2> end
irb(main):022:1> end
=> nil
irb(main):023:0> class Accessor
irb(main):024:1> cattr_accessor ne, :two
irb(main):025:1> def self.fetch_one( )
irb(main):026:2> @@one
irb(main):027:2> end
irb(main):028:1> end
=> nil
irb(main):029:0> Accessor.one = "James"
=> "James"
irb(main):030:0> Accessor.two = "Gray"
=> "Gray"
irb(main):031:0> Accessor.one
=> "James"
irb(main):032:0> Accessor.two
=> "Gray"
irb(main):033:0> Accessor.fetch_one
NameError: uninitialized class variable @@one in Accessor
from (irb):26:in `fetch_one'
from (irb):33
from (null):0
Everything works as expected, save fetch_one(). Why does it not return
"James"?
Thanks.
James Edward Gray II