On 5/17/07, Daniel Berger <> wrote:
> Is there a way to freeze instance variables in Ruby in order to make
> them single assignment? I'm just wondering if there's a way to
> simulate Erlang in this regard as a way to avoid side effects.
>
> I don't want to simply not define (or undefine) a setter method
> because you could still get at the instance variable via
> instance_variable_set. Redefining instance_variable_set won't work
> either, because that method is apparently not called when performing
> direct assignment of instance variables. I tried calling the freeze
> method on the instance variables directly but that didn't seem to work
> either.
Do it differently:
require 'digest/md5'
class Module
def erl_accessor(*names)
names.each do |name|
var = "@_#{Digest::MD5.hexdigest(rand(65536).to_s + name.to_s)}"
define_method(name) { || instance_variable_get(var) }
define_method("#{name}=") { |v|
instance_variables.include? var and raise "Cannot change @#{name}."
instance_variable_set(var, v)
}
end
nil
end
end
class Foo; erl_accessor :bar, :baz; end
foo = Foo.new
foo.bar = 5
Since your actual instance variables aren't related to the names, you
can only access through accessors.
-austin
--
Austin Ziegler *
*
http://www.halostatue.ca/
*
*
http://www.halostatue.ca/feed/
*