16

How can I perform interpolation within single quotes?

I tried something like this but there are two problems.

string = 'text contains "#{search.query}"'
  1. It doesn't work
  2. I need the final string to have the dynamic content wrapped in double quotes like so:

    'text contains "candy"'
    

Probably seems strange but the gem that I'm working with requires this.

2
  • get search.query to return it's result wrapped in double quotes? Commented Feb 16, 2013 at 16:35
  • 2
    You never have to use single quotes - the created string doesn't know if it was created from a single quoted literal, double quoted literal, other literal or from other string operations Commented Feb 16, 2013 at 16:37

3 Answers 3

22

You can use %{text contains "#{search.query}"} if you don't want to escape the double quotes "text contains \"#{search.query}\"".

0
7
'Hi, %{professor}, You have been invited for %{booking_type}. You may accept, reject or keep discussing more about this offer' % {professor: 'Mr. Ashaan', booking_type: 'Dinner'}
1
  • Just a note, String.format is preferable over % (according to Rubocop). +1 good sir, thanks Commented Oct 18, 2015 at 19:46
-2

Use

%q(text contains "#{search.query}") 

which means start the string with single quote. Or if you want to start with double quote use:

%Q(text contains '#{text}')
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.