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.
Yes, an instance variable can be defined as a constant.
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.
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.
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
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