Search code examples
ruby-on-railsrubyxpathnokogiriopen-uri

using variable in xpath on ruby with nokogiri


require 'nokogiri'
require 'open-uri'

1.upto(10) do |x|
url = TOPSECRET
page = Nokogiri::HTML(open(url))

title = page.xpath('//span[@class="tit"][#{x}]').inner_html

puts "#{x}, #{title}"
end

the error occurs [#{x}] <= here

how can I fix this?


Solution

  • The problem is with your use of single quotes instead of double quotes.

    change this:

    title = page.xpath('//span[@class="tit"][#{x}]').inner_html
    

    to this:

    title = page.xpath("//span[@class=\"tit\"][#{x}]").inner_html
    

    for proper variable expansion. Note also the escaping of internal double quotes.