Weird behavior with hpricot and variable assignment

R

ridcully

Hi,

Could someone please help me to understand the difference of:

html = Hpricot( "<div><div></div></div>" )
(html/'/div').each do |item|
x = (item/'/div')[0].to_html
p x
end

output: "<div></div>"

and

html = Hpricot( "<div><div></div></div>" )
(html/'/div').each do |item|
p (item/'/div')[0].to_html
end

gives "undefined method `[]' for nil:NilClass (NoMethodError)" in line
3

Shouldn't the code snippets semantically be the same?

Thanks,
Andreas
 
Y

yermej

Hi,

Could someone please help me to understand the difference of:

html = Hpricot( "<div><div></div></div>" )
(html/'/div').each do |item|
x = (item/'/div')[0].to_html
p x
end

output: "<div></div>"

and

html = Hpricot( "<div><div></div></div>" )
(html/'/div').each do |item|
p (item/'/div')[0].to_html
end

gives "undefined method `[]' for nil:NilClass (NoMethodError)" in line
3

Try your second example in irb and you'll get a warning (or I do,
anyway):

(irb):5: warning: don't put space before argument parentheses

This means you're essentially doing this:

(p(item/'/div'))[0].to_html

and since p returns nil, you're calling [] on nil. Try this instead:

p((item/'/div')[0].to_html)
 
R

ridcully

Try your second example in irb and you'll get a warning (or I do,
anyway):

(irb):5: warning: don't put space before argument parentheses

This means you're essentially doing this:

(p(item/'/div'))[0].to_html

and since p returns nil, you're calling [] on nil. Try this instead:

p((item/'/div')[0].to_html)

You're right, it does work if I add parentheses.
Still I don't fully understand why this is happening. The [] operator
obviously has a high presendence, because this of course does work:

p [1, 2, 3][0].to_s

Also this does work fine:

p (html/'/div')[0].to_html

I don't really see the difference to my second example. What am I
missing here?

Andreas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top