我在 TDD 中构建它很开心:
def nested_match_sum(data)
grouped = data.group_by(&:last)
grouped.values.map do |array|
array.inject(nil) do |result, elem|
if result
elem[1] = array_position_sum(elem[1], result[1])
end
elem
end
end
end
def array_position_sum(first, second)
first.zip(second).map do |couple|
couple.first + couple.last
end
end
require 'rspec/autorun'
describe "#nested_match_sum" do
let(:data) do
[
["abc", [0.0, 1.0, 2.0, 3.0], "Testing"],
["efg", [1.0, 2.0, 3.0, 4.0], "Testing"]
]
end
it "groups by last element and aggregates the sum" do
expect(nested_match_sum(data)).to eq(
[["efg", [1.0, 3.0, 5.0, 7.0], "Testing"]]
)
end
context "giving multiple keys" do
let(:data) do
[
["abc", [0.0, 1.0, 2.0, 3.0], "Testing"],
["efg", [1.0, 2.0, 3.0, 4.0], "Testing"],
["abc", [0.0, 1.0, 2.0, 3.0], "Another"],
["ghj", [2.0, 3.0, 4.0, 5.0], "Another"]
]
end
it "works aswell" do
expect(nested_match_sum(data)).to eq([
["efg", [1.0, 3.0, 5.0, 7.0], "Testing"],
["ghj", [2.0, 4.0, 6.0, 8.0], "Another"]
])
end
end
end
describe "#array_position_sum" do
let(:first) { [1, 2, 3] }
let(:second) { [4, 5, 6] }
it "sums two arrays by position" do
expect(array_position_sum(first, second)).to eq(
[5, 7, 9]
)
end
end