Having recently started programming in Ruby, I noticed one small language feature that is really giving me a hard time — variables that start with a capital letter are automatically constants.
While I understand that this is by design, and does really help in most cases, it becomes a problem once one starts writing algorithms. By that I mean code that requires efficient and easy distinction between variables — say, n and N.
Here is a very simplistic example (I’m aware it’s not a fully valid/rubyesque code, but I hope it illustrates my point):
def average(array)
N = 0
array.each { |n| N += n }
N/array.length.to_f
end
Another example is subscripts — say, while doing a calculation in a physics problem, having F_friction and F_weight would be helpful but impossible in Ruby.
So, the question is: is there an accepted way of dealing with these variable names?
Usually the solution is just to choose much more meaningful names. E.g.
Why is
F_weighthelpful. F is for Force?Fine
force_weight, erm no:force_mass. After all weight is a force.Now if you were talking about N as in the set of natural numbers, I could see some point if N wasn’t a local variable.