How to block a Ruby link?

I use Object#freeze to freeze the value of an object. I can write a function to deep freeze the complex structure of an object. But none of them will allow me to assign 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 completely freeze an identifier?

+4
source share
2 answers

There is no way to do this. If the variable is a constant (starts with a capital letter), you will see a warning if you try to reassign it, but the reassignment will still occur. eg.

 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> 
+3
source

You should use the rb_define_readonly_variable function from the 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 message.

 NameError: $var is a read-only variable 
+3
source

Source: https://habr.com/ru/post/1316044/


All Articles