Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there such a thing as a constant instance variable in Ruby?

Tags:

ruby

My googlefu sucks and was unable to find information on this.

Basically I want to have a instance variable that is visible only within the scope of a class/module but is also immutable.

I am new to Ruby and apologize if this question doesn't make much sense.

like image 607
PolandSpring Avatar asked Aug 02 '10 22:08

PolandSpring


People also ask

Can a constant be an instance variable?

Yes, an instance variable can be defined as a constant.

How do you define a constant variable in Ruby?

Ruby ConstantsConstants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally. Constants may not be defined within methods.

Can a Ruby module have instance variables?

In the Ruby programming language, an instance variable is a type of variable which starts with an @ symbol. An instance variable is used as part of Object-Oriented Programming (OOP) to give objects their own private space to store data.


1 Answers

class MyClass
  def initialize
    class << self
      FOO=1
    end
  end
  def foo
    class << self
      FOO
    end
  end
end

Naturally, you'll want to use the method foo wherever possible to read the value.

A simpler equivalent would be

class MyClass
  def initialize
    def foo; 1; end
  end
end
like image 136
Ken Bloom Avatar answered Nov 15 '22 03:11

Ken Bloom