The following segment of a JSON file needs to be transformed, essentially flattening it to a single hash for sizes
"sizes" : {
"small" : {
"w" : "680",
"h" : "261",
},
"large" : {
"w" : "878",
"h" : "337",
},
"medium" : {
"w" : "878",
"h" : "337",
}
while the child attributes are accessible as:
parent['sizes'].each do |size|
w: size['w'],
h: size['h'],
label: size
end
will not function, as the whole hash will be loaded for the label. How can the hash's identity string only be captured?
CodePudding user response:
For hashes each
calls the block once for each key in hash, passing the key-value pair as parameters.
Like this:
parent['sizes'].each do |key, size|
# format your preferred output here
# key is small, large, medium
# and size is {"w"=>"680", "h"=>"261"}, ...
# for example
{
w: size['w'],
h: size['h'],
label: key
}
end