2012-07-20 59 views
1

我正在构建一个html元素,类名和它们的计数树。红宝石嵌套散列语法和结构

我该如何使用正确的语法来构造这段代码?

$html = { 

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

} 

我对嵌套散列语法感到困惑。感谢您帮助我设置直线。

回答

3

在定义了HTML元素之后,您不再指定另一个散列,而是指定一个列表并从问题标题中直接嵌套另一个散列。因此,你不开始用方括号,但与另一大括号:

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

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

,它将打印:

看看的Hash构造文档,有不同的方式来初始化散列,也许你会找到更直观的方法。

4

一个简单的方法来构建一个HTML树可能是:

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

哪里html[0][:_tag]是标签名,而其他属性是通过html[0][attr]访问。根元素是一个数组,因为相同类型的多个元素(多个p aragraphs)可以存在于相同的名称空间中,并且散列只会存储最后添加的元素。

一个更高级的实施例,这将允许嵌套内容:

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