You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Ruby高效优雅地将多值逗号分隔Hash转为哈希数组?

Ruby风格实现:将多值逗号分隔的哈希转换为哈希数组

核心实现

下面是简洁且符合Ruby风格的写法,能动态适配任意数量的键和值:

def expand_hash(hash)
  hash.transform_values { |val| val.split(',') }.values.transpose.map do |values|
    hash.keys.zip(values).to_h
  end
end

代码解析

  1. transform_values { |val| val.split(',') }:将原哈希中每个逗号分隔的字符串值分割成数组,得到类似 {name: ["cheese", "test"], uid: ["1", "2"]} 的结构。
  2. .values.transpose:提取所有值数组并转置,把同一位置的元素归为一组,得到 [["cheese", "1"], ["test", "2"]]。
  3. .map { |values| hash.keys.zip(values).to_h }:将每组转置后的元素与原哈希的键一一配对,转换为新的哈希对象。

测试示例

基础场景

input = {name: "cheese,test", uid: "1,2"}
expand_hash(input)
# => [{:name=>"cheese", :uid=>"1"}, {:name=>"test", :uid=>"2"}]

多键多值场景

input = {name: "a,b,c", uid: "1,2,3", tag: "food,snack,fresh"}
expand_hash(input)
# => [
#      {:name=>"a", :uid=>"1", :tag=>"food"},
#      {:name=>"b", :uid=>"2", :tag=>"snack"},
#      {:name=>"c", :uid=>"3", :tag=>"fresh"}
#    ]

单值边界场景

input = {name: "orange", uid: "5"}
expand_hash(input)
# => [{:name=>"orange", :uid=>"5"}]

注意事项

  • 该实现默认所有键对应的分割后值数组长度一致,如果存在长度不一致的情况,transpose 会抛出 IndexError。若需要兼容这种情况,可以根据需求添加长度校验或取最短/最长数组进行处理。

内容的提问来源于stack exchange,提问作者user3049364

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 15:20:24