简体   繁体   中英

Ruby deep_merge on an array of hashes

I want to merge an attribute on hashes nested inside an array, which is nested inside a hash.

ball = {
  name: "Hugh",
  colors: [
    {name: "Blue"},
    {name: "Red"}
  ]
}

I tried to use deep merge , but I think it only supports merging into a nested hash, not an array of hashes.

balls.deep_merge(size: "small")

Output:

ball = {
  name: "Hugh",
  colors: [
    {name: "Blue"},
    {name: "Red"}
  ],
  size: "small"
}

Expected output.

ball = {
  name: "Hugh",
  colors: [
    {name: "Blue", size: "small"},
    {name: "Red", size: "small"}
  ]
}

You can iterate over the array (depending on how abstract you need it to be).

ball[:colors].each {|c| c[:size] = "small"}

Or, assuming you have a "balls" array, this would work for mass assignment.

balls.each {|ball| ball[:colors].each {|c| c[:size] = "small"} }

There is nothing that can do this automagically, I'm afraid. There is no way for a program to know that { size: "small" } is meant to go into each hash of the colors key and not in any other.

But you've got a good start here formulated the question almost as a unit test, so I have no doubt you can find a manual way to do this with TDD!

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