1

I'm building a tree of html elements, class names and their counts.

How would I structure this code with the proper syntax?

$html = {

    :p => [
        { 'quote' => 10 },
        { 'important' => 4 }
    ],
    :h2 =>  [
        { 'title' => 33 },
        { 'subtitle' => 15 }
    ]

}

I'm confused by the nested hash syntax. Thanks for the help setting me straight.

2 Answers 2

4

A simple way to structure a HTML tree could be:

html = [
  { _tag: :p, quote: 10, important: 4 },
  { _tag: :h2, title: 33, subtitle: 15 },
]

Where html[0][:_tag] is the tag name, and other attributes are accessible through html[0][attr]. The root element is an array since multiple elements of the same type (multiple paragraphs) could exist in the same namespace and a hash would only store the last added one.

A more advanced example which would allow nested contents:

tree = { _tag: :html, _contents: [
  { _tag: :head, _contents: [
    { _tag: :title, _contents: "The page title" },
  ]},
  { _tag: :body, id: 'body-id',  _contents: [
    { _tag: :a, href: 'http://google.com', id: 'google-link', _contents: "A link" },
  ]},
]}
Sign up to request clarification or add additional context in comments.

Comments

3

After defining the HTML element you don't assign another hash, but a list and from your question title I guess you want to nest another hash directly. Thus you do not start with a square bracket, but with another curly brace:

$html = {
    :p => { 'quote' => 10, 'important' => 4 },
    :h2 =>  { 'title' => 33, 'subtitle' => 15 }
}

#Example
puts $html[:p]['quote']

Which will print:

10

Take a look at the constructor documentation of Hash, there are different ways to initialize hashes, maybe you find a more intuitive one.

Comments

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.