设计思路
- 深度遍历数组找出特定键值:
- 使用递归方法来实现深度遍历。对于数组中的每个元素,如果是哈希,检查是否存在特定键
unique_key
,如果存在则将其值添加到结果数组中。如果元素是数组,则递归调用遍历方法。对于其他基本类型,直接跳过。
- 合并商品哈希:
- 首先,创建一个空的结果哈希。遍历每个输入的商品哈希,以商品名
product_name
作为键。如果结果哈希中已经存在该商品名的键,则更新价格和库存。价格更新为(原价格 * 原数量 + 当前价格)/(原数量 + 1),库存相加。如果不存在,则直接将当前商品哈希的信息添加到结果哈希中。
代码实现
module DataProcessor
def self.find_key_values(arr, key = 'unique_key')
result = []
arr.each do |element|
case element
when Hash
result << element[key] if element.key?(key)
result.concat(find_key_values(element.values, key))
when Array
result.concat(find_key_values(element, key))
end
end
result.compact
end
def self.merge_product_hashes(hashes)
result = {}
hashes.each do |hash|
product_name = hash[:product_name]
if result.key?(product_name)
old_hash = result[product_name]
new_price = ((old_hash[:price] * old_hash[:count] + hash[:price]) / (old_hash[:count] + 1)).round(2)
new_stock = old_hash[:stock] + hash[:stock]
new_count = old_hash[:count] + 1
result[product_name] = {product_name: product_name, price: new_price, stock: new_stock, count: new_count}
else
hash[:count] = 1
result[product_name] = hash
end
end
result.values.map { |v| v.except(:count) }
end
end
测试用例
require 'test/unit'
class TestDataProcessor < Test::Unit::TestCase
def test_find_key_values
arr = [
{unique_key: 'value1'},
[1, 2, {unique_key: 'value2'}],
{nested: {unique_key: 'value3'}}
]
assert_equal(['value1', 'value2', 'value3'], DataProcessor.find_key_values(arr))
end
def test_merge_product_hashes
hashes = [
{product_name: '商品1', price: 100, stock: 50},
{product_name: '商品2', price: 200, stock: 30},
{product_name: '商品1', price: 150, stock: 20}
]
expected = [
{product_name: '商品1', price: 116.67, stock: 70},
{product_name: '商品2', price: 200, stock: 30}
]
assert_equal(expected, DataProcessor.merge_product_hashes(hashes))
end
end