Thursday, February 7, 2013

Ruby's Single Quote And Double Quote

As a Rails tester, I've been using Ruby's single quote and double quote exchangeably until I run into the following problem. After writing so many tests, I'm thinking about metaprogramming the testing as certain tests are the same for all the models. I wrote a test template file that will be loaded for each new test file I'm going to write. This template file is basically pure text, but I want it to be a little bit more dynamic. For example, I want it to generate today's date. So I write something like the following in the template file:

# Author
#    David on #{Date.today.strftime("%m/%d/%y")}
=>
# Author
#    David on #{Date.today.strftime("%m/%d/%y")} 


However, when I read this template file into my test file, these strings appear as exactly the same as they appear in the template, as oppose to showing today date. So I searched on the Internet and find that Ruby treats single quotes and double quotes really differently: the double quotes interpret the interpolation and the escaped characters within the string, while single quotes do not do these two things. So performance-wise, using double quote is gonna take longer if interpolation or escaped character is involved.

Now back to my problem, the reason that the date is not shown correctly is that the content of the template is read as being wrapped with single quotes. So how can we tell Ruby that we want the content as to be wrapped with double quotes? We can use the double quote mark "%Q{}". Everything within the delimiter will appear as if they are wrapped with double quotes (see below).

%Q(# Author
#    David on #{Date.today.strftime("%m/%d/%y")})
=>
# Author
#    David on 02/06/2013

No comments:

Post a Comment