Q:

How to use variable in Nokogiri contains

I have an XML file like:
<main>
  <key>xxx</key>
  <key>yyy</b>
  <key>zzz</key>
</main>

To check whether the XML has a node with text "yyy", I can use:
xml = Nokogiri::XML(file)
if xml.at('main/key:contains("yyy")')
  #code will go here
end

But if the text value is a variable how can I use the same statement?
Note: I have tried below solution and it doesn't work:
var = "yyy"
if xml.at("main/key:contains(#{var})")

A:

"main/key:contains(#{var})"

interpolates to to
"main/key:contains(yyy)"

Note the absence of quotes. You want this:
"main/key:contains(\"#{var}\")"

or more prettily
%Q{main/key:contains("#{var}")}

and some clever escaping would also help if you are not sure about the content of var.

