freeze string fails to freeze ???

R

Robert Klemme

=> "qwer"

should'nt that throw and exception ???

No, the *object* is frozen. This has no effects on the *variable*.
TypeError: can't modify frozen string
from (irb):4:in `<<'
from (irb):4
from :0

Kind regards

robert
 
O

Olivier Renaud

Le jeudi 15 mars 2007 16:35, (e-mail address removed) a =E9crit=A0:
=3D> "asdf"


=3D> "asdf"


=3D> "qwer"

should'nt that throw and exception ???

No, because calling the freeze method prevents from modifying the object, i=
t=20
doesn't prevent from modifying the variable. Remember that a variable is ju=
st=20
a way to give a name to an object, but it is not tied to this object foreve=
r.

So, your code doesn't raise an exception, but this one does :

irb(main):001:0> a=3D"abc"
=3D> "abc"
irb(main):002:0> a.freeze
=3D> "abc"
irb(main):003:0> a << 'd'
TypeError: can't modify frozen string
from (irb):3:in `<<'
from (irb):3

What you are looking for is closer of a constant, actually :

irb(main):004:0> A=3D"abc"
=3D> "abc"
irb(main):005:0> A=3D"def"
(irb):5: warning: already initialized constant A

=2D-=20
Olivier Renaud
 
F

Fergal J Byrne

=> "qwer"

should'nt that throw and exception ???

freeze is a method on the object referenced by a,
not on the variable a (a is just a name, not the
object itself).

a = 'abcd'
a.freeze

# a[2]='w' raises
# ./freezetest.rb:7:in `[]=': can't modify frozen string (TypeError)

This causes an exception because you are trying to modify the
frozen object.

a = 'defg'

This does not, because the object (which up to now was
referenced by a) is not changed. a now refers to a
different object.

Try it with a constant:

A = 'abcd'
A = 'defg' # raises a warning: already initialized constant A



--

Regards,

Fergal Byrne - Technical Director


Adnet: Web Builders to the Design Industry

http://www.adnet.ie/ t:+353 1 855 8951 aim/skype:FergByrne

=== We've Moved! 63 Lower Gardiner Street, Dublin 1 ===
 
R

Rick DeNatale

No, because calling the freeze method prevents from modifying the object, it
doesn't prevent from modifying the variable. Remember that a variable is just
a way to give a name to an object, but it is not tied to this object forever.

Is it just me or has the confusion between variables and objects been
coming up more frequently than usual of late?
 
O

Olivier Renaud

Le jeudi 15 mars 2007 23:16, Rick DeNatale a =E9crit=A0:
Is it just me or has the confusion between variables and objects been
coming up more frequently than usual of late?

Not more often than the elsif/elseif confusion :D

=2D-=20
Olivier Renaud
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top