How do you grab the value of a constant if it is inside a class << self?
example
class A
class << self
B = “HI”
end
end
A::B does not work. How would you go about grabbing the value for B?
Sorry for such a noob question. Thanks!
How do you grab the value of a constant if it is inside a class << self?
example
class A
class << self
B = “HI”
end
end
A::B does not work. How would you go about grabbing the value for B?
Sorry for such a noob question. Thanks!
Ben J. wrote:
How do you grab the value of a constant if it is inside a class << self?
example
class A
class << self
B = “HI”
end
endA::B does not work. How would you go about grabbing the value for B?
You’ve explicitly defined the constant inside the metaclass (singleton
class) of A.
I’d say it’s better not to define the constant there in the first place,
but define it under A:
irb(main):001:0> class A
irb(main):002:1> B = “HI”
irb(main):003:1> class << self
irb(main):004:2> def test
irb(main):005:3> puts “I say #{B}”
irb(main):006:3> end
irb(main):007:2> end
irb(main):008:1> end
=> nil
irb(main):009:0> A.test
I say HI
=> nil
irb(main):010:0> A::B
=> “HI”
But if you really want to store a constant in a metaclass, it is
possible to get at it:
irb(main):001:0> class A
irb(main):002:1> class << self
irb(main):003:2> B = “HI”
irb(main):004:2> end
irb(main):005:1> end
=> “HI”
irb(main):006:0> A::B
NameError: uninitialized constant A::B
from (irb):6
from :0
irb(main):007:0> class Class
irb(main):008:1> def meta
irb(main):009:2> class <<self; self; end
irb(main):010:2> end
irb(main):011:1> end
=> nil
irb(main):012:0> A.meta::B
=> “HI”
I wrote a SingletonTutorial on the rubygarden.org wiki, but
unfortunately that site appears to have closed.
Regards,
Brian.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs