Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: accessing a class constant for instance of class

Tags:

ruby

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.

like image 709
randombits Avatar asked Jan 13 '23 12:01

randombits


2 Answers

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..

like image 96
Arup Rakshit Avatar answered Jan 30 '23 10:01

Arup Rakshit


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
like image 41
Roger Avatar answered Jan 30 '23 11:01

Roger