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

Ruby 3中能否直接通过哈希值的模式匹配获取对应哈希键?

Ruby 3模式匹配:直接操作哈希查找包含指定值的键

直接对哈希进行模式匹配的实现

可以直接通过哈希的模式匹配完成需求,无需先转为数组。利用Ruby 3.1及以上版本支持的哈希任意键绑定+模式匹配特性,就能直接定位到值包含目标数字的键:

def find_the_key(a_hash, a_number)
  case a_hash
  in **rest, the_key: [*, ^a_number, *]
    the_key
  else
    :key_not_found
  end
end

h = {
  x: [1, 2, 3],
  y: [11, 12, 13],
  z: [100, 101],
}

puts find_the_key(h, 13)   # => :y
puts find_the_key(h, 999)  # => :key_not_found

这段代码的逻辑是:

  • **rest 匹配并忽略哈希中所有不符合后续条件的键值对
  • the_key: [*, ^a_number, *] 会自动匹配任意键(将键名绑定到the_key变量),同时检查该键对应的值是否是包含a_number的数组(^a_number表示引用外部变量,而非创建新变量)

其他基于模式匹配的实现方式

除了直接对哈希做case匹配,还可以结合Hash#find和模式匹配的in语句来实现:

def find_the_key(a_hash, a_number)
  a_hash.find do |key, value|
    value in [*, ^a_number, *]
  end&.first || :key_not_found
end

这里通过find遍历哈希键值对,用value in [*, ^a_number, *]判断值是否符合包含目标数字的数组模式,最后返回匹配到的键,未匹配则返回:key_not_found。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 04:40:54