Why the string interpolation is not working inside the Nokogiri method `#search` ?

10 views
Skip to first unread message

Love U Ruby

unread,
Sep 2, 2013, 2:29:00 PM9/2/13
to rubyonra...@googlegroups.com
Why the string interpolation is not working inside the Nokogiri method
`#search` ?

require 'nokogiri'

doc = Nokogiri::HTML::Document.parse <<-eotl
<div>
<p>foo</p>
<p>foo</p>
<p>bar</p>
</div>
eotl

doc.class # => Nokogiri::HTML::Document

class Person
attr_accessor :name
end

ram = Person.new
ram.name="foo"
ram.name # => "foo"
doc.search('//div/p[text()= "#{ram.name}"]').to_a.size
# => 0

Where am I doing wrong ? please help!

--
Posted via http://www.ruby-forum.com/.

Jordon Bedwell

unread,
Sep 2, 2013, 3:09:59 PM9/2/13
to rubyonra...@googlegroups.com
You are not wrapping it in a "" or %Q{}...:
1. doc.search("//div/p[text()= \"#{ram.name}\"]").to_a.size
2. doc.search(%Q{//div/p[text()= "#{ram.name}"]}).to_a.size

Love U Ruby

unread,
Sep 2, 2013, 3:18:24 PM9/2/13
to rubyonra...@googlegroups.com
@Jordon - Thank you very much - it worked like a charm!!

require 'nokogiri'

doc = Nokogiri::HTML::Document.parse <<-eotl
<div>
<p>foo</p>
<p>foo</p>
<p>bar</p>
</div>
eotl

doc.class # => Nokogiri::HTML::Document

class Person
attr_accessor :name
end

ram = Person.new
ram.name="foo"
ram.name # => "foo"
doc.search("//div/p[text()= \"#{ram.name}\"]").to_a.size
# => 2
Reply all
Reply to author
Forward
0 new messages