1

I am trying to parse a nested array of Symbols into HTML my input is:

[[:html,
  [:head, [:title, "Hello World"]],
  [:body, [:h1, "Hello World"], [:p, "This is your parser"]]]]

My intended Output is:

<html>
  <head>
    <title>Hello World</title>
  </head>
  <body>
    <h1> Hello World </h1>
    <p> This is your parser</p>
  </body>
</html>

My Method is:

def to_html(data)
 if( data.is_a?(Array))

   open_map = data.map do |item|
    if( item.is_a?(Array))
      to_html(item)
    else
      if( item.is_a?(Symbol))
        "<"+ item.to_s + ">"
      else
        item.to_s
      end
    end
  end

  close_map = data.map do |item|
    if( item.is_a?(Array))
      to_html(item)
    else
      if( item.is_a?(Symbol))
        "</"+ item.to_s + ">"
      end
    end
  end
      open_map.join(' ')   + close_map.join(' ')
  else
    data.to_s
  end
end

This basically works except that it recurses too much in that I think the two recursive calls to to_html results in double output

ie:

<html> 
 <head>
   <title> Hello World
   </title>
 </head> 
   <title> Hello World
  </title>
<body>
. . . .

and so on

I think I need to nest the recursions or else filter the results

How can I fix this?

1
  • I think your input have one extra layer of [] Commented Jul 29, 2014 at 22:16

1 Answer 1

2

If you assume the first element of each array is the tag name, then it can be simplified to:

def to_html(data)
  if (data.is_a?(Array))
    tag = data[0]
    children = data[1..-1]
    return "<#{tag}>" + children.map {|x| to_html(x)}.join(' ') + "</#{tag}>"
  else
    return data
  end
end

print to_html([:html,
               [:head, [:title, "Hello World"]],
               [:body, [:h1, "Hello World"], [:p, "This is your parser"]]])

prints

<html><head><title>Hello World</title></head> <body><h1>Hello World</h1> <p>This is your parser</p></body></html>
Sign up to request clarification or add additional context in comments.

3 Comments

The Array is a tree of nested arrays of symbols so it has has to recurse into each array and convert the item to a string the surround the item with < >
@tbrooke, it does recursively print each tag (see updated answer with output). However, the input does not have the outer array as your sample input.
You are correct the extra layer came from the output of a parser that feed this function - I pulled it out and this works fine Thank You

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.