简体   繁体   中英

Ruby: join hash keys

I have the following hash:

{
  a: {
    b: {
     c1: "c1 value",
     c2: "c2 value",
     c3: {
       d: "d value
    }
  }
}

How I can convert him to next result:

{
  "a.b.c1" => "c1 value",
  "a.b.c2" => "c2 value",
  "a.b.c3.d" => "d value"
}

Here is a modified solution:

h = {
  a: {
    b: {
     c1: "c1 value",
     c2: "c2 value",
     c3: {
       d: "d value"
     }
    }
  }
}

def flatten_hash(h)
  return { "" =>  h } unless h.is_a?(Hash)
  Hash[h.map { |a,v1| flatten_hash(v1).map { |b,v2| [[a,b].map(&:to_s).delete_if(&:empty?).join('.'), v2] } }.flatten(1)]
end

p flatten_hash(h)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM