in coding

Ruby dup() and clone() with frozen strings

I’m exhuming some 5-year old Ruby RDF code, and in the process finding a few things got broken while I was in the time capsule. Here in the shiny future, I found myself hitting an unfamiliar “can’t modify frozen string” error. It all worked just fine back in the hazy summer of 2002, I’m sure. I think. Back then SPARQL didn’t exist, Redland’s rapper utility was called rdfdump, the RDFCore syntax cleanup wasn’t finished, Ruby was more permissive about good parenthesis habits, and so on. But that’s another pile of trouble. This frozen string thing was a bit puzzling, but I got to learn about dup() and clone() at least.

On some investigation, it seems the string in question is being passed in from the command line, and apparently the contents of ARGV are frozen. My first guess was that I’d just clone the string object in question, and all would be well. After some fiddling around, I learned the difference between clone() and dup(): the latter doesn’t preserve frozen-ness: I wanted dup(). All seems well. Back to fixing the real problems; details below for the curious, and as a memory jog next time I run into this.

Maybe next time I emerge from the time capsule, Ruby will be fully Unicode happy?

 a="foo"
=> "foo"

a.frozen?
=> false

a.freeze
=> "foo"

b=a.clone
=> "foo"

a.frozen?
=> true

b=a.dup
=> "foo"

b.frozen?
=> false

c=a.clone
=> "foo"
c.frozen?
=> true
Add Comment Register