2013-10-23 200 views
0

我有一個Ruby散列,例如:Ruby 1.9的解析散成HTML表格

{"monkeys"=> {"hamburgers" => ["love", "eat"], 
       "boulders" => ["hate", "throw"]}, 
"stonemasons" => {"boulders" = > ["love", "use"], 
        "vandals" => ["hate", "sue"]} 
} 

它可以有幾乎任何級別(我可以把哈希散列內任意次數)的深度。它始終具有數組作爲最終值。

如何在不使用Rails的情況下將它解析爲如下所示的HTML表格,並且最好只使用標準庫?

<table> 
    <tr> 
    <th rowspan="2">monkeys</th> 
    <th>hamburgers</th> 
    <td>love</td> 
    <td>eat</td> 
    </tr> 
    <tr> 
    <th>boulders</th> 
    <td>hate</td> 
    <td>throw</td> 
    </tr> 
    <tr> 
    <th rowspan="2">stonemasons</th> 
    <th>boulders</th> 
    <td>love</td> 
    <td>use</td> 
    </tr> 
    <tr> 
    <th>vandals</th> 
    <td>hate</td> 
    <td>sue</td> 
    </tr> 
</table> 
+0

希望這種聯繫將幫助你... HTTP://stackoverflow.com/questions/4588196/turn- a-ruby-hash-into-html-list – LHH

+0

它在一定程度上有所幫助,但主要問題在於:1)計算羣體; 2)找到新的tr並妥善放置它們。 –

+0

看起來很奇怪,你想要一些'tr'有2'th'和2'td',而其他人只有'th'和2'td'。你確定你不需要爲結果表使用'rowspan'而不是'colspan'嗎? –

回答

1

應該這樣做:

h = {"monkeys"  => {"hamburgers" => ["love", "eat"], 
         "boulders" => ["hate", "throw"]}, 
    "stonemasons" => {"boulders" => ["love", "use"], 
         "vandals" => ["hate", "sue"]}} 


def parse_data(html, data, new_line = true) 

    klass = data.class 

    # Use the class to know if we need to create TH or TD 
    case 
    when klass == Hash 
    data.each do |key, value| 

     # Start a new row 
     if new_line 
     html << '<tr>' 
     new_line = false 
     end 

     # Check if we need to use a rowspan 
     if value.class == Array || value.count == 1 
     html << "<th>#{key}</th>" 
     else 
     html << "<th rowspan=\"#{value.count}\">#{key}</th>" 
     end 

     # Parse the content of the hash (recursive) 
     html, new_line = parse_data(html, value, new_line) 
    end 
    when klass = Array 
    data.each do |item| 
     html << "<td>#{item}</td>" 
    end 

    # We end the row and flag that we need to start a new one 
    # if there is anymore data 
    html << '</tr>' 
    new_line = true 
    end 

    return html, new_line 
end 

html = '<table>' 
html, new_line = parse_data(html, h) 
html << '</table>' 

puts html 

輸出:

<table> 
    <tr> 
    <th rowspan="2">monkeys</th> 
    <th>hamburgers</th> 
    <td>love</td> 
    <td>eat</td> 
    </tr> 
    <tr> 
    <th>boulders</th> 
    <td>hate</td> 
    <td>throw</td> 
    </tr> 
    <tr> 
    <th rowspan="2">stonemasons</th> 
    <th>boulders</th> 
    <td>love</td> 
    <td>use</td> 
    </tr> 
    <tr> 
    <th>vandals</th> 
    <td>hate</td> 
    <td>sue</td> 
    </tr> 
</table> 
+0

看起來不錯,謝謝!但是,如果我有兩個哈希值作爲另一個哈希值的值,它會起作用嗎?就像,'k = {「in USA」=> h,「in UK」=> h}'? –

+0

它應該。它解析散列結構,直到它找到一個數組,然後它結束該行,並開始一個新的。因此,只要更深的嵌套元素是數組,就可以嵌套任意數量的散列。 –

+0

我現在嘗試了它,可悲的是,它沒有。它給出了「在美國」和「在英國」的行數爲2,而它們應該是4(最終值的數量) –