MST

星途 面试题库

面试题:Ruby数组与哈希在复杂场景下的设计与应用

设计一个Ruby模块,该模块有两个主要功能:1. 接收一个包含不同类型数据的数组,数组中的元素可能是哈希、数组或者其他基本类型,需要对其进行深度遍历,找出所有哈希中特定键(如 'unique_key')对应的值,并汇总到一个新的数组中;2. 接收多个哈希,每个哈希代表一个商品的信息,格式为{product_name: '商品1', price: 100, stock: 50},要求合并这些哈希,相同商品名的价格取平均值,库存相加。请详细说明设计思路,并给出完整的代码实现及测试用例。
27.5万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 深度遍历数组找出特定键值
    • 使用递归方法来实现深度遍历。对于数组中的每个元素,如果是哈希,检查是否存在特定键 unique_key,如果存在则将其值添加到结果数组中。如果元素是数组,则递归调用遍历方法。对于其他基本类型,直接跳过。
  2. 合并商品哈希
    • 首先,创建一个空的结果哈希。遍历每个输入的商品哈希,以商品名 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