Ruby: single quotes and double quotes

Another random thing that I noticed and/or remembered as I was writing some more code.  Single quotes v’s double quotes in ruby on rails.  You’ll note that your controllers all generate with single quote strings, such as:

    format.html { redirect_to @account, notice: 'Account was successfully updated.' }

But double quote strings also work.  I was sort of interchanging them, until I remembered the difference.  A single quote string is a literal – it’s always used exactly as is.  A double quote string does pattern matching, so you can write something like:

    format.html { redirect_to @account, notice: 'Account was successfully updated for account #{@account.Name}.' }

Which substitutes in the account name within the string.  Because the double quote form needs to check to see if there’s variable substitution in there, it’s a little slower than the single quote form if you don’t actually have any variables in there.  So the rule is: use single quotes if your string is static, use double quotes if it has variables or other funkiness in it.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s