【问题标题】:Ruby nested hash syntax & structureRuby 嵌套哈希语法和结构
【发布时间】:2012-07-20 08:45:07
【问题描述】:

我正在构建一个包含 html 元素、类名及其计数的树。

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

$html = {

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

}

我对嵌套的哈希语法感到困惑。感谢您帮助我直截了当。

【问题讨论】:

    标签: ruby hash


    【解决方案1】:

    一种构造 HTML 树的简单方法是:

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

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

    允许嵌套内容的更高级示例:

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

    【讨论】:

      【解决方案2】:

      在定义 HTML 元素后,您没有分配另一个哈希,而是一个列表,并且从您的问题标题中我猜您想直接嵌套另一个哈希。因此,您不是从方括号开始,而是从另一个花括号开始:

      $html = {
          :p => { 'quote' => 10, 'important' => 4 },
          :h2 =>  { 'title' => 33, 'subtitle' => 15 }
      }
      
      #Example
      puts $html[:p]['quote']
      

      将打印的内容:

      10

      看看Hash的构造函数文档,初始化哈希有不同的方法,也许你会找到更直观的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-21
        • 2019-08-08
        • 2021-02-03
        • 1970-01-01
        • 2015-04-16
        相关资源
        最近更新 更多