Thursday, March 24, 2011

Not as constant as one might think

One of those Ruby gotchas that has to lead to a bug report before it finally burns itself to memory:

irb(main):001:0> TMP="1234"
=> "1234"
irb(main):002:0> t = TMP
=> "1234"
irb(main):003:0> t.succ!
=> "1235"
irb(main):004:0> TMP
=> "1235"

Eh? Isn't TMP a constant, after all?

Apparently this has to do with t being assigned a reference to a (shared) String:

irb(main):005:0> a="456"
=> "456"
irb(main):006:0> b=a
=> "456"
irb(main):007:0> b.succ!
=> "457"
irb(main):008:0> a
=> "457"

Needless to say, this will do the trick:

t = TMP.dup

This will raise an error on t.succ!, for obvious reasons :

TMP='123'
TMP.freeze

Moral: "Constants" are NOT frozen and their values are not copied on assignment!

No comments:

Post a Comment