【问题标题】:ruby hash of arrays that contain arrays包含数组的数组的 ruby​​ 哈希
【发布时间】:2014-04-19 04:38:52
【问题描述】:

我正在学习 ruby​​,但在处理包含多维数组的哈希时遇到了一些麻烦。

例如,我正在尝试使用作为城市名称的键创建哈希。然后,在那个城市内部,我想要一个包含数据数组的数组。

它应该看起来像这样:

hash = {"chicago" => [["carl","blue"], ["ross", "red"]], "new york" => [ ["linda", "green"], ["john", "purple"], ["chris", "black"]]}

我怎样才能做到这一点,我怎样才能访问/附加到每个键内的数组?

我一直在尝试类似的东西:

hash["chicago"][].push["new person", "color"]

谢谢,我知道这很简单,但我似乎无法用 Ruby 来解决问题。

【问题讨论】:

    标签: ruby hash


    【解决方案1】:

    将事情分解成步骤会很有帮助。所以,我们知道hash是散列,hash['chicago']是数组的数组,所以从这里我们可以看出我们要推入hash['chicago']。这意味着您的代码唯一的错误是您有一对额外的大括号。所以我们得到:

    hash['chicago'].push ['new person', 'yellow or something']
    

    【讨论】:

    • 很好的解释。谢谢!
    • 在学习识别push 是一个方法(而不是像数组一样的东西)时也很方便,所以hash['chicago'].push(['new person', 'yellow or something']) 将与上面相同。
    • 知道了,顺便说一句,这是让我在 ruby​​ 中绊倒的东西。好像有 3 种语法方式可以做所有事情,这会让人感到困惑
    【解决方案2】:

    在这些情况下,我通常使用默认 proc 定义散列,该过程确定当给定键不存在于散列中时应该发生什么:

    hash = Hash.new {|h,k| h[k] = [] }
    

    在这种情况下,默认值是一个空数组。向哈希中添加新数据就很简单了:

    hash["chicago"] << ["carl", "blue"]
    

    一个警告 - 如果您进行查找,缺失值将表示为一个空数组。您可以使用 fetch 而不是方括号表示法解决此问题:

    hash.fetch("chicago", nil) #=> [["carl", "blue"]]
    hash.fetch("new york", nil) #=> nil
    

    【讨论】:

      【解决方案3】:

      这是一种方法:

      hash = Hash.new { |h,k| h[k] = [] }
      hash["chicago"].push ["carl","blue"]
      hash["chicago"].push ["ross", "red"]
      hash
      # => {"chicago"=>[["carl", "blue"], ["ross", "red"]]}
      
      hash["new york"].push ["linda", "green"]
      hash["new york"].push ["john", "purple"]
      
      hash
      # => {"chicago"=>[["carl", "blue"], ["ross", "red"]],
      #     "new york"=>[["linda", "green"], ["john", "purple"]]}
      

      来自new {|hash, key| block } → new_hash

      如果指定了一个block,它将使用散列对象和键调用,并且应该返回默认值。如果需要,将值存储在哈希中是块的责任。


      如何访问?

      使用 Hash#fetchHash#[] 相同,这适合您的需要。

      【讨论】:

        猜你喜欢
        • 2015-05-07
        • 2015-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-28
        相关资源
        最近更新 更多