Search code examples
ruby-on-railsxmlrexml

each_element not behaving as expected


When I'm in irb and I do something like this:

node_list.each_element { |e| puts e.text }

It works and prints one line of text per element returned (plus I think it returns the xml object). However, when I head over to rails and have things moving between controllers, helpers, views and layouts it just dumps the xml object.

I should mention that for good reasons I'm using rails 1.2.3 and ruby 1.8.7.

Gratzi!


Solution

  • So the issue your having is that puts writes to console and not the template. Also, in ruby the a method will return by default its last object. So your method as written will loop through @child1, print each's text to the console, and then return the @child1 object at which point your erb tags of <%= %> tells it print the object (@child1 in this case)

    You have two options, either you can move it out into the template:

    <% tol_get_names(@child1) do |e| %> #note just <% and not <%=
      <%= e.text %>
    <% end %>
    

    Or build your method so that it loops through building a string and then returns that string instead of the original object:

    def tol_get_names(child)
      texts = [] #empty array for all our values
      child.each_element { |e| 
        texts << e.text #add the text string to our array
      end
      texts.join(", ") #build a string and seperate it with a comma
    end
    

    Several ways you could write this type of method, but this is my usual way.