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

Ruby如何从哈希数组中仅保留指定数组内定义的键值对

实现方案

你可以通过 Ruby 内置的 Hash#slice 方法结合数组遍历完成需求,完整实现代码如下:

test = [{ 'id' => '123',
      'circulating_supply' => '18846675',
      'max_supply' => '21000000',
      'market_cap' => '1165693461932',
      'market_cap_dominance' => '0.4277',
      'num_exchanges' => '393',
      'num_pairs' => '66516',
      'num_pairs_unmapped' => '5168' },
      { 'id' => '321',
      'circulating_supply' => '4121',
      'max_supply' => '324134',
      'market_cap' => '9999',
      'market_cap_dominance' => '0.4204',
      'num_exchanges' => '943',
      'num_pairs' => '2341',
      'num_pairs_unmapped' => '4231' }]

a = ['market_cap', 'num_exchanges', 'num_pairs_unmapped']
# 构造需要保留的键列表,同时包含id和a中定义的字段
allowed_keys = a + ['id']
# 遍历每个哈希,仅保留指定键
result = test.map { |hash| hash.slice(*allowed_keys) }
# 直接修改原test变量
test = result

运行后test的值就和你给出的预期输出完全一致。

  • 代码里的*allowed_keys是把数组拆成独立参数传给slice方法,slice会返回仅包含传入键的新哈希,不会修改原哈希对象。如果需要直接修改原哈希,可以把slice替换为slice!,无需额外赋值。
  • 如果你使用的Ruby版本低于2.5(不支持原生slice方法),可以用下面的兼容写法:
result = test.map do |hash|
  hash.select { |key, _| allowed_keys.include?(key) }
end

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:39:03