Variables in REXML

Real nuby question.

This works fine…
irb> puts root.elements[‘foo/bar[3]’].text
three

I can’t work out how to do this…
irb> i = 3
irb> puts root.elements[‘foo/bar[i]’].text

I keep getting error message
NoMethodError: undefined method `text’ for nil:NilClass

I’ve tried defining “i” every which way – [i], [@i] and others.

irb> $i = 3
irb> [${i}]
doesn’t error, but it outputs as if i = 1.

All of the REXML examples for text nodes that I have been able to track
down have the index hard coded, or use .each

Can someone point me in the right direction?

I think this is the string interpolation you’re looking for:

root.elements[“foo/bar[#{i}]”].text

Paul.

I can’t work out how to do this…
irb> i = 3
irb> puts root.elements[‘foo/bar[i]’].text

Please try:
puts root.elements[“foo/bar[#{i}]”].text

On Mon, 27 Mar 2006 21:24:48 +0900, Jerome Zago wrote:

I can’t work out how to do this…
irb> i = 3
irb> puts root.elements[‘foo/bar[i]’].text

Please try:
puts root.elements[“foo/bar[#{i}]”].text

Aha! The double quotes did the trick.

I had unsucessfully tried
puts root.elements[‘foo/bar[#{i}]’].text

Thanks a million!