I have a class that looks like the following:
class Foo
MY_CONST = "hello"
ANOTHER_CONST = "world"
def self.get_my_const
Object.const_get("ANOTHER_CONST")
end
end
class Bar < Foo
def do_something
avar = Foo.get_my_const # errors here
end
end
Getting a const_get uninitialized constant ANOTHER_CONST (NameError)
Assuming I'm just doing something silly in as far as Ruby scope goes. I'm currently using Ruby 1.9.3p0 on the machine where I'm testing this code.
Now working:
class Foo
MY_CONST = "hello"
ANOTHER_CONST = "world"
def self.get_my_const
const_get("ANOTHER_CONST")
end
end
class Bar < Foo
def do_something
avar = Foo.get_my_const
end
end
Bar.new.do_something # => "world"
Your below part is not correct:
def self.get_my_const
Object.const_get("ANOTHER_CONST")
end
Inside the method get_my_const
,self is Foo
. So remove Object
,it will work..
You can use const like:
Foo::MY_CONST
Foo::ANOTHER_CONST
You can gey a array of constants:
Foo.constants
Foo.constants.first
With your code:
class Foo
MY_CONST = 'hello'
def self.get_my_const
Foo::MY_CONST
end
end
class Bar < Foo
def do_something
avar = Foo.get_my_const
end
end
x = Bar.new
x.do_something
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With