调用在ruby中的哈希变平。古怪

时间:2016-06-23 18:02:08

标签: ruby

说我有以下哈希:

error_hash = {
    :base => [
        [0] [
            [0] "Address is required to activate"
        ]
    ]
}

这些结果是否奇怪?

[18] pry(#<Api::UsersController>)> error_hash.flatten
[
    [0] :base,
    [1] [
        [0] [
            [0] "Address is required to activate"
        ]
    ]
]
[19] pry(#<Api::UsersController>)> error_hash.flatten(1)
[
    [0] :base,
    [1] [
        [0] [
            [0] "Address is required to activate"
        ]
    ]
]
[20] pry(#<Api::UsersController>)> error_hash.flatten(2)
[
    [0] :base,
    [1] [
        [0] "Address is required to activate"
    ]
]
[21] pry(#<Api::UsersController>)> error_hash.flatten(3)
[
    [0] :base,
    [1] "Address is required to activate"
]

我原本期望.flatten等于flatten(3),或者换句话说,我希望.flatten递归展平,直到evereything在一个数组中。

1 个答案:

答案 0 :(得分:2)

为什么在documentation建议不这样做的时候,你会期望flatten采取递归行动?

您可以使用以下命令扩展哈希的功能:

class Hash
  def flatten_deepest
    self.each_with_object({}) do |(key, val), h|
      if val.is_a? Hash
        val.flatten_to_root.map do |hash_key, hash_val|
          h["#{key}.#{hash_key}".to_sym] = hash_val
        end
      else
        h[k] = val
      end
    end
  end
end

然后执行:

 error_hash.flatten_deepest

我认为你有了这个主意。