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

如何使用Ruby将多个数组转换为指定格式的哈希?

嘿,这个转换需求在Ruby里有好几种简洁的实现方式,我给你拆解几个方案:

方法一:用each_with_object结合索引查找

这种方式逻辑直观,适合刚接触Ruby的朋友理解:

arr = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
# 提取第一个子数组作为哈希的键集合
keys = arr.first
# 剩下的子数组是需要提取值的来源
values_sources = arr[1..-1]

# 遍历每个键,构建哈希
result = keys.each_with_object({}) do |key, hash|
  # 找到当前键在原键数组中的索引,然后从每个值来源数组中取对应位置的元素
  hash[key] = values_sources.map { |sub_arr| sub_arr[keys.index(key)] }
end

puts result.inspect
# => {1=>[6, 11], 2=>[7, 12], 3=>[8, 13], 4=>[9, 14], 5=>[10, 15]}

方法二:利用transpose转置(更高效)

如果你的数组元素比较多,上面的index查找会有性能损耗,用transpose转置数组的方式更高效:

arr = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
# 转置数组:把原数组的行和列互换,得到[[1,6,11], [2,7,12], [3,8,13], ...]
transposed_arr = arr.transpose

# 遍历转置后的每个子数组,第一个元素是键,剩下的是值数组
result = transposed_arr.each_with_object({}) do |item, hash|
  hash[item.first] = item[1..-1]
end

puts result.inspect
# => {1=>[6, 11], 2=>[7, 12], 3=>[8, 13], 4=>[9, 14], 5=>[10, 15]}

一行代码简化版

Ruby的语法糖可以让我们把这个逻辑压缩成一行,非常简洁:

arr = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
result = arr.transpose.to_h { |key, *values| [key, values] }

puts result.inspect
# 同样输出目标哈希

这里的*values是Ruby的splat运算符,用来捕获子数组中除第一个元素外的所有元素,直接作为值数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:01:54