Forum: Ruby Variables in REXML

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
54Sandgroper (Guest)
on 2006-03-27 16:14
(Received via mailing list)
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?
Paul B. (Guest)
on 2006-03-27 16:24
(Received via mailing list)
I think this is the string interpolation you're looking for:

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

Paul.
Jerome Zago (Guest)
on 2006-03-27 16:24
(Received via mailing list)
> 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
54Sandgroper (Guest)
on 2006-03-27 17:59
(Received via mailing list)
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!
This topic is locked and can not be replied to.