Ruby中将数组内嵌哈希转为单键多值哈希 | Rails API从Redis取数处理
把数组内嵌哈希转成单键多值哈希的Ruby/Rails实现方案
嘿,这事儿在Ruby/Rails里处理起来很顺手,给你几个实用的解决办法:
1. 用Ruby原生的to_h方法(Ruby 2.1+)
如果你的目标是把每个元素的id作为键,对应的完整哈希作为值,直接用to_h配合块就能搞定:
# 假设这是你从Redis拿到的原始数据 authors = [ { "id": 1, "name": "Stephenie Meyer", "created_at": "2018-04-17T07:40:50.417Z", "updated_at": "2018-04-17T07:40:50.417Z" }, { "id": 2, "name": "V.C. Andrews", "created_at": "2018-04-17T07:40:50.613Z", "updated_at": "2018-04-17T07:40:50.613Z" }, { "id": 3, "name": "Sophie Kinsella", "created_at": "2018-..." } ] # 转换操作 result = authors.to_h { |author| [author[:id], author] }
转换后你会得到这样的结构:
{ 1 => { "id": 1, "name": "Stephenie Meyer", ... }, 2 => { "id": 2, "name": "V.C. Andrews", ... }, 3 => { "id": 3, "name": "Sophie Kinsella", ... } }
2. 用each_with_object做自定义处理
要是你不想保留完整哈希,只想把特定字段作为值(比如只存name),用each_with_object可以灵活调整:
result = authors.each_with_object({}) do |author, hash| # 这里可以按需修改值的内容,比如组合多个字段 hash[author[:id]] = author[:name] end
这样得到的就是{ 1 => "Stephenie Meyer", 2 => "V.C. Andrews", 3 => "Sophie Kinsella" }这种精简版的哈希。
3. Rails专属的index_by快捷方法
既然你在做Rails应用,那必须试试Rails封装的index_by,专门干这种数组转键值哈希的活儿,代码更简洁:
result = authors.index_by { |author| author[:id] }
注意事项
- 如果原始哈希的键是字符串类型(比如
"id"),请对应使用author["id"]来取值,避免出现nil。 - 若数组中存在重复的
id,后续元素会覆盖之前的,所以要保证数据源中id的唯一性。
内容的提问来源于stack exchange,提问作者user3576036
相关产品推荐
相关产品推荐

