Search code examples
rubyvariablesconstantsmutable

Ruby Equivalent of C++ Const?


I'm learning Ruby in my spare time, and I have a question about language constructs for constants. Does Ruby have an equivalent of the C++ const keyword to keep variables from being modified? Here's some example code:

first_line   = f.gets().chomp()
column_count = first_line.split( %r{\s+} ).size()
print column_count, "\n"

I'd like to declare column_count to be const, because I use it below in my program and I really don't want to modify it by mistake. Does Ruby provide a language construct for doing this, or should I just suck it up and realize that my variables are always mutable?

Response to comments:

'The most likely cause of "accidental" overwriting of variables is, I'd guess, long blocks of code.' I agree with the spirit of your point, but disagree with the letter. Your point about avoiding long blocks of code and unnecessary state is a good one, but for constants can also be useful in describing the design of code inside of the implementation. A large part of the value of const in my code comes from annotating which variables I SHOULD change and which I shouldn't, so that I'm not tempted to change them if I come back to my code next year. This is the same sentiment that suggests that code that uses short comments because of good variable names and clear indentation is better than awkwardly written code explained by detailed comments.

Another option appears to be Ruby's #freeze method, which I like the look of as well. Thanks for the responses everyone.


Solution

  • Variables that start with a capital letter are constants in Ruby. So you could change your code to this:

    first_line   = f.gets().chomp()
    Column_count = first_line.split( %r{\s+} ).size()
    print Column_count, "\n"
    

    Now you'll get a warning if you try to modify Column_count.