Trouble understanding const_set()

Hello,

I’m trying to understand why the following code is giving me an error. It
seems like it isn’t finding Foo::Constant (which doesn’t exist), but why
isn’t it looking for Bar::Constant, instead?

As you can see, `self’ is Bar, not Foo:

irb(main):001:0> class Foo
irb(main):002:1> def Foo.foo
irb(main):003:2> const_set ‘Constant’, 'just a string’
irb(main):004:2> puts self.inspect
irb(main):005:2> puts Constant
irb(main):006:2> end
irb(main):007:1> end
nil
irb(main):008:0> class Bar < Foo
irb(main):009:1> end
nil
irb(main):010:0> Bar.foo
Bar
NameError: uninitialized constant Constant at Foo
from (irb):5:in `foo’
from (irb):10
irb(main):011:0> Bar::Constant
"just a string"

Any help would be much appreciated,

Chris

“Chris Pine” wrote

Any help would be much appreciated,

This has little to do with const_set - its essentially a
consequenz of general ``constant’’ scoping rules .

···

class Foo
def Foo.foo
const_set ‘Constant’, ‘just a string’
puts self.inspect
puts Constant
end
Constant = ‘surprise’
end

$a = Object.new

class Bar < Foo
def $a.show
puts Constant
end

end

Bar.foo
$a.show

Bar
surprise
just a string

/Christoph

“Chris Pine” nemo@hellotree.com wrote in message
news:132b01c2bb42$737ea330$6401a8c0@MELONBALLER…

Hello,

I’m trying to understand why the following code is giving me an error.
It
seems like it isn’t finding Foo::Constant (which doesn’t exist), but
why
isn’t it looking for Bar::Constant, instead?

As you can see, `self’ is Bar, not Foo:

irb(main):001:0> class Foo
irb(main):002:1> def Foo.foo
irb(main):003:2> const_set ‘Constant’, ‘just a string’
irb(main):004:2> puts self.inspect

irb(main):005:2> puts Constant

irb(main):005:2> puts const_get(‘Constant’)

irb(main):006:2> end
irb(main):007:1> end
nil
irb(main):008:0> class Bar < Foo
irb(main):009:1> end
nil
irb(main):010:0> Bar.foo
Bar
just a string
nil

The change to line 5 averts the [uninitialized constant] error.

Your example shows the answer to a possible supplementary question:
“Must Bar.const_get(‘Constant’) be used thereafter ?”

irb(main):011:0> Bar::Constant
“just a string”

… happily, no.

daz