From: Brian Candler Date: 2009-12-06T19:17:24+09:00 Subject: Re: Why doesn't Ruby "compile" strings? I単aki Baz Castillo wrote: >> When you are using the string literals, the interpreter doesn't know what >> you are going to do with that string literal, so it's not really safe for >> it to assume that it can use a single ruby object to represent all >> instances of it. > > Why not? It's obviously a string writen in the script, with no variables > into > it and so... Suppose you do: 10.times do puts "hello" end The interpreter has no way of knowing that puts does not mutate the argument passed to it. This is a silly example, but you might have done: alias :old_puts :puts def puts(x) old_puts x x.replace "rubbish" end So it is forced to create a new string object each time round the loop. It's a shame that Ruby doesn't have immutable strings. Symbols are the closest, but they have different semantics to strings. If the literal syntax "xxx" gave a *frozen* String, then it would be safe to re-use it. But then if you wanted to append to a string, you'd have to write: a = "".dup a << "stuff" or perhaps a = String.new a << "stuff" Regards, Brian. -- Posted via http://www.ruby-forum.com/.