我有一个这样的杂烩:

{
 "category" => ["sport", "gaming", "other"],
 "duration" => 312,
 "locations" => {
    "688CQQ" => {"country" => "France", "state" => "Rhône-Alpes"},
    "aUZCAQ" => {"country" => "France", "state" => "Île de France"}
  }
}

如果值是散列,我希望通过展平一个值来将其还原为散列而不嵌套。在最终值中,我应该只有整数、字符串或数组,如下所示:
{
  "category" => ["sport", "gaming", "other"],
  "duration" => 312,
  "locations_688CQQ_country" => "France",
  "locations_688CQQ_state" => "Rhône-Alpes",
  "locations_aUZCAQ_country" => "France",
  "locations_aUZCAQ_state" => "Île de France"
}

我想要一个可以与任何级别的嵌套一起工作的函数。我怎么能用鲁比呢?

最佳答案

这里有一个递归方法,其中h是您的散列。

def flat_hash(h)
  h.reduce({}) do |a, (k,v)|
    tmp = v.is_a?(Hash) ? flat_hash(v).map { |k2,v2| ["#{k}_#{k2}",v2]}.to_h : { k => v }
    a.merge(tmp)
  end
end

关于ruby - 拼合哈希并连接 key ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34270973/

10-13 08:03