In this question I found an interesting detail about scope of a final variable in Java. I don’t know Java good enough, but I think that final is identical to a constant in Ruby.
In C++ this is possible:
for(int i = 0; i < 5; ++i){
const int c = i * 5;
std::cout << c << std::endl;
}
Trying to change the value during the loop is not possible though and gives you a compile time error.
I was curious to see how Ruby would handle this, started irb and wrote this code to test it:
5.times do |x|
XPI = x * Math::PI
puts x
end
the result was
0.0
(irb):27: warning: already initialized constant XPI
3.141592653589793
(irb):27: warning: already initialized constant XPI
6.283185307179586
(irb):27: warning: already initialized constant XPI
9.42477796076938
(irb):27: warning: already initialized constant XPI
12.566370614359172
=> 5
So my question: Is there a way to assign a constant at the beginning of a loop that gets initialized for each loop iteration without creating warning messages? It could have some real world use cases, when I want to make a calculation based on the iterator variable and then make sure, the result does not get changed for the remaining loop.
Nothing you need every single day, but I’m just curious.
There seems to be no strict equivalent to Java’s final in ruby. However, you could use
remove_const(which is a private method inModule) to get rid of the constant (and the warnings) at the end of the loop: