Ruby Strings – How to Put String With Single Quotes in Single Quotes

I set up a series of Ruby unit tests to better explore SED.  Basically, I invoke it as follows:

def sed_result(input_str, sed_str)
     %x[echo #{input_str} | #{sed_str}]

It worked well, until I did this:

assert_equal("howdy\n", sed_result("howdy from Texas", "sed 's/\([a-zA-Z]*\).*/\1/'"))

Assigning the latter string to a variable in ruby produces a different string, because strings in double quotes are processed: “sed ‘s/([a-zA-Z]*).*/01/'”

For example, when I want to do string interpolation, I have double quotes instead of single quotes as follows:  “The value of foo is #{foo}” to the string “The value of foo is bar”.  This time, I don’t want any processing of the string, but want to pass it as is.  Thus, I need to use single quotes, except my string contains single quotes. What to do?

Well, the following use of %q[] is the same as using single quotes, and worked well:

assert_equal("howdy\n", sed_result("howdy from Texas", %q[sed 's/\([a-zA-Z]*\).*/\1/']))

Additionally, you can use %Q[] in place of double quotes.


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s