25 May 2009

Ways to create String

If I have to create a string I always used to use Q along with curly braces like this.

f = 'foo'      
puts %Q( This is me #{f} ) #=> This is me foo       

Today accidentally I found out that I don’t need that capital Q.

f = 'foo'      
puts %{ This is me #{f} } #=> This is me foo 

Not only that I can use parenthesis () in stead of curly braces.

f = 'foo'      
puts %( This is me #{f} ) #=> This is me foo 

All these solutions also work with text being spread across multi line.

Here are my complete test cases.

f = 'foo'
puts %( This is me #{f} ) #=> This is me foo 
puts %Q( This is me #{f} ) #=> This is me foo 
puts %q( This is me #{f} ) #=> This is me #{f}
puts %{ This is me #{f} } #=> This is me foo 
puts %Q{ This is me #{f} } #=> This is me foo