CD-RUM CD-RUM - 4 months ago 8
Ruby Question

Ruby: adding arrays of hashes (don't ask), delete if found

I asked a similar question recently that I solved here, but I need to ask it again because my platform is unforgiving and the structure must be as follows:

"variables": [
{
"box": "info_top",
"content": "Default info_top content"
},
{
"box": "info_bottom",
"content": "Default info_bottom content"
},
{
"box": "info_top",
"content": "NEW INFO TOP CONTENT"
}
]


In short, I want to overwrite the first
info_top
hash in the above array with the second
info_top
. The method that builds this array looks like this:

def variables
(template_variables + user_variables).sort_by do |k, _v|
order.index k['box'].to_sym
end
end


I need
user_variables
to replace any hash found in
template_variables
based on the hash's value of the
box
key.

Answer

If your arrays look like this:

template_variables = [
  {
    "box" => "info_top",
    "content" => "Default info_top content"
  },
  {
    "box" => "info_bottom",
    "content" => "Default info_bottom content"
  }
]

user_variables = [
  {
    "box" => "info_top",
    "content" => "NEW INFO TOP CONTENT"
  }
]

You can get there like this:

(user_variables + template_variables).uniq { |hash| hash["box"] }

 => [{"box"=>"info_top", "content"=>"NEW INFO TOP CONTENT"}, {"box"=>"info_bottom", "content"=>"Default info_bottom content"}] 

Notice that user_varliables goes first when adding the arrays together.

EDIT:

So the final version should look like this:

def variables
  (user_variables + template_variables).uniq { |hash| hash["box"] }.sort_by do |k, _v|
    order.index k['box'].to_sym
  end
end