D
D
Demigodd2019-05-03 14:36:21
ruby
Demigodd, 2019-05-03 14:36:21

How to raise all elements in a hash one level up and remove that hash?

For example, there is such a hash:

{
  "aaa"=>{"age"=>11},
  "bbb"=>{
    "age"=>11,
    "child"=>{
      "child_1"=>{"age"=>11},
      "child_2"=>{"age"=>11}
    }
  },
  "ccc"=>{"age"=>11}
}

How to get this from this:
{
  "aaa"=>{"age"=>11},
  "child_1"=>{"age"=>11},
  "child_2"=>{"age"=>11},
  "ccc"=>{"age"=>11}
}

That is, who has a child , raise all of its elements one level up and remove it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-05-03
@Demigodd

data = data.reduce({}){|acc, (k, v)| acc.update(v['child'] || {k => v})}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question