2012-07-20 57 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" }, 
    ]}, 
]}