Dave Rau
Dave Rau

Reputation: 103

Ruby nested hash syntax & structure

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.

Upvotes: 1

Views: 2814

Answers (2)

Konrad Reiche
Konrad Reiche

Reputation: 29553

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.

Upvotes: 3

mogelbrod
mogelbrod

Reputation: 2315

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" },
  ]},
]}

Upvotes: 4

Related Questions