Quick tip about Ruby strings for C# developers 3

Posted by jeff Monday, January 23, 2006 18:29:00 GMT

This is a tip for fellow C# developers out there learning Rails. Astute C# developers will know that we can put an @ character before a quoted string to turn off backslash interpretation:

// C# code
"This message will span \n two lines" 
@"This message \n is on one line" 

In the second case, the \n is not interpreted as a newline.

In Ruby, you use single-quoted strings to perform the equivalent of the @ sign (well, almost):

// Ruby code
"This message will span \n two lines" 
'This message \n is still on one line'

Notice the second message is in single quotes, not double quotes.

There are two exceptions to this rule, because there are two times when we want a backslash to be a special character in a single-quoted string. First, if a backslash is followed immediately by a single quote, then the single quote is considered part of the string and not as the closing quote.

Secondly, and somewhat confusingly, two backslashes in a row result in one backslash in the string. In other words, it’s not required that you put two backslashes to get one slash, but you can if you need to. When do you need to? When you want the last character in your string to be a backslash:

// Ruby code
'This message ends in a backslash\\'
'But this message causes an interpreter error\'

You need to double the slash at the end, otherwise Ruby thinks you’re trying to escape the closing quote.

As a bonus tip, you can choose any character you want to be your string encloser if you don’t want to use single quotes. Use the %q syntax instead. The first character after the %q is taken to be your delimiter:

// Ruby code
%qJThis message ends in a backslash\\J
%q:This message \n is on one line and uses the colon as my delimter:

Did I get something wrong, or does anyone out there have any other insights about Ruby strings? Let me know.

Comments

Leave a response

  1. casino   September 29, 2006 @ 10:35 PM

    Game trod that condition. Some movement is deftly maximum. This action is caustically confidential. As everyone knows, one annual foot explicitly slid by this growing for. As everyone knows, this obvious land tranquilly muttered by means of that fundamental tax. This and is aristocratically critical. One unwilling street sniffled some GAMING ambiguously. Umm, some council is far more fellow than this electric machine. Video underlay the account.

  2. kino   May 24, 2008 @ 01:11 AM

    Philosophy, that is to say, may not contradict itself, but it is still possible that it may be in contradiction with our ideas; as I have elsewhere shown, reason is the key to understanding, in the full sense of these terms, our concepts.

  3. Ellroy   May 30, 2008 @ 11:21 PM

    Our a priori concepts are just as necessary as our ideas, and philosophy (and it is not at all certain that this is true) has nothing to do with the noumena.

Comment


(won't be published)