tags:

views:

34

answers:

2

I use Object#freeze to freeze the value of an object. I can write a function to deep-freeze a complex object structure. But neither will prevent me from assigning a new value to an object.

$O=cl()
$O.thorough_freeze
$O[:file] = "makefile"      # => TypeError
$O[:commands][0] = "clean"  # => TypeError
$O = "reticulate"           # => TypeError

In C I say

int const * const ptr = argv;

How can I thoroughly freeze an identifier?

+1  A: 

There isn't a way to do this. If a variable is a constant (starts with a capital letter) then you will see a warning if you attempt to reassign it but the reassignment will still take place. e.g.

irb(main):008:0> MyConst = my_obj
=> #<MyClass:0x2b8a66c>
irb(main):009:0> MyConst = my_other
(irb):9: warning: already initialized constant MyConst
=> #<MyClass:0x2b854b4>
mikej
+1  A: 

You have to use the rb_define_readonly_variable function from a C extension, for example:

VALUE var;

void Init_my_extension(void) {
  var = Qnil; // set this to the initial value.

  rb_define_readonly_variable("$var", &var);
}

Then, when you try to do this from ruby:

$var = 123

you will get an error.

NameError: $var is a read-only variable
Adrian