I've got the following code that does the job:
pairs = {
pair1: {
first: [{a: 1}, {b: 2}, {c:3}],
second: [{a: 1}, {b: 2}, {c:3}],
},
pair2: {
first: [{a: 1}, {b: 2}, {c:3}, {d:4}],
second: [{a: 1}, {b: 2}, {c:3}],
},
pair3: {
first: [{a: 1}, {b: 2}, {c:3}],
second: [{a: 1}, {b: 2}, {c:3}],
}
}
pairs.flat_map { |_, t| t[:first] }.reduce Hash.new, :merge
pairs.flat_map { |_, t| t[:second] }.reduce Hash.new, :merge
I would like to know how it would be possible to make this more elegant by extracting common code into a method. Common code being map block. I did read up on Ruby's blocks but I had some difficult time understanding it and could use some help. My initial attempt was:
def reusable_map_block
pairs.flat_map(yield).reduce Hash.new, :merge
end
reusable_map_block { |t| t[:first] }
def reusable_map_block(&block)
pairs.flat_map(block.call).reduce Hash.new, :merge
end
reusable_map_block { |t| t[:first] }
def reusable_map_block(&block)
pairs.flat_map(block.call).reduce Hash.new, :merge
end
pairs.reusable_map_block { |t| t[:first] }
But it's yet not clicking to me. This is just a syntax I'm experimenting with - ultimate goal is giving developer a control which hash to select for further processing and using function as an argument felt natural coming from JS/TS/.NET.