开发者

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

开发者 https://www.devze.com 2023-01-10 11:04 出处:网络
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

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.


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


Ruby constants aren't very constant: they're not immutable, and you can assign another value to them and all you get is a warning. See the question Constant Assigment Bug in Ruby?


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

(The approaching as Ken's one.)

0

精彩评论

暂无评论...
验证码 换一张
取 消