# Variables in REXML

**URL:** <https://www.ruby-forum.com/t/variables-in-rexml/56033>\
**Category:** Ruby\
**Created:** [March 27, 2006, 2:14pm UTC](https://www.ruby-forum.com/t/variables-in-rexml/56033 "2006-03-27T14:14:05Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![54Sandgroper](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/5/ed8c4c/32.png) [@54Sandgroper](https://www.ruby-forum.com/u/54Sandgroper)\
**Post date:** [March 27, 2006, 2:14pm UTC](https://www.ruby-forum.com/t/variables-in-rexml/56033/1 "2006-03-27T14:14:05Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![54Sandgroper](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/5/ed8c4c/32.png) [@54Sandgroper](https://www.ruby-forum.com/u/54Sandgroper)\
**Post date:** [March 27, 2006, 2:24pm UTC](https://www.ruby-forum.com/t/variables-in-rexml/56033/2 "2006-03-27T14:24:23Z")

</div>

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

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

Paul.

---

<div class="post-metadata">

**Author:** ![54Sandgroper](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/5/ed8c4c/32.png) [@54Sandgroper](https://www.ruby-forum.com/u/54Sandgroper)\
**Post date:** [March 27, 2006, 2:24pm UTC](https://www.ruby-forum.com/t/variables-in-rexml/56033/3 "2006-03-27T14:24:54Z")

</div>

> 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

---

<div class="post-metadata">

**Author:** ![54Sandgroper](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/5/ed8c4c/32.png) [@54Sandgroper](https://www.ruby-forum.com/u/54Sandgroper)\
**Post date:** [March 27, 2006, 3:59pm UTC](https://www.ruby-forum.com/t/variables-in-rexml/56033/4 "2006-03-27T15:59:08Z")

</div>

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!
