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

My googlefu sucks and could not find information about it.

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

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

+5
source share
3 answers
class MyClass
  def initialize
    class << self
      FOO=1
    end
  end
  def foo
    class << self
      FOO
    end
  end
end

Naturally, you will want to use a method foowhere possible to read the value.

A simpler equivalent would be

class MyClass
  def initialize
    def foo; 1; end
  end
end
+3
source

Ruby : , , , , . . Ruby?

+1

I wrote a gem for this occasion. http://rubygems.org/gems/instancevalue

(approaching like Ken.)

0
source

All Articles