I think growing a string with << is an expensive operation. Since once the allocated memory is full, it will cost O(n) to copy the entire string to a new location. If we are carrying out m insertions, this could take O(mn).<p>The way I have been building strings is to store the m strings in an Array and then join() it at the end (which should be only O(n)). The m small objects need to be allocated in both cases, the only difference being that we hold on to those and join them later on.<p>Am I missing something? I have never measured the performance on either of the these operations so I could be off the mark here.
Something in my computer-science-student background feels unsettled when I can use a language for years and still learn new tricks (or often, that I've forgotten that I've learned) about common functionality such as string interpolation...but I do love a lot of Ruby's tricks.<p><pre><code> if path =~ %r{^/assets/mobile/img}
...
end
</code></pre>
I knew about `%r` but hadn't realized that it escapes forward-slashes while leaving other regex symbols intact. But with the previous explanation of `%q`, in which arbitrary delimiters can be used, it makes sense...curly braces simply replace `/` as the delimiter, and `/` simply retains its non-specialness in regex...saves me a lot of writing `Regex.escape("/path/to")`.<p>Another regex notation that I recently learned (elsewhere) and now love to abuse:<p><pre><code> "He is 32-years old"[/\d+/] # => "32"
</code></pre>
as opposed to:<p><pre><code> "He is 32-years old".match(/\d+/)[0]</code></pre>
These are some good tips. If you are into the Ruby language and want more, I recommend checking out Ruby Tapas <a href="http://www.rubytapas.com/" rel="nofollow">http://www.rubytapas.com/</a> . I have no affiliation with it, just happy customer.
notice that this is wrong<p><pre><code> x ||= y # equivalent to:
x || x = y
</code></pre>
it's actually something slightly different (or at least it was some years ago).