----- Original Message -----
From: HarryO <harryo / zipworld.com.au>
Newsgroups: comp.lang.ruby
To: ruby-talk ML <ruby-talk / ruby-lang.org>; <undisclosed-recipients: ;>
Sent: Monday, July 09, 2001 8:31 PM
Subject: [ruby-talk:17588] Re: Constants and Variables
> > Because that freezes the object that MAX_SIZE references, not MAX_SIZE
> > itself.
>
> Of course! Sorry, I should have realised that.
>
> However ... I figured I could then do
>
> max_size = 10
> max_size.freeze
> max_size = 5 # 3
> puts "max = #{max}" # 4
>
> and line 3 would produce an error, line 4 would print 10.
>
> However, that doesn't work. I get no errors and max_size prints as 5.
>
> Am I just really thick, or is there a bug here?
You're not thick... you're just not yet thinking in Ruby.
Freezing does NOT affect a variable. Not at all! Say it to
youself... :)
Freezing affects the *object* referred to by the variable.
Thus an operation that actually tries to change a frozen object
will fail.
x = "Hello"
x.freeze
x[0] = "J"
# -:3:in `[]=': can't modify frozen string (TypeError)
# from -:3
Think of it this way: x isn't frozen; it's "Hello" that's frozen.
But an operation that merely changes a variable to refer to
some other object is fine.
x = "Hello"
x.freeze
x = "Jello"
# The object "Hello" is still frozen... though if it is not
# referred to anywhere, it will be garbage collected now...
Sometimes the distinction is unclear (to me, anyway).
When in doubt, try it out.
Hal