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

如何提取JSON哈希的标识字符串?sizes哈希遍历取值异常解决方案

问题描述

需要将一段JSON中的sizes嵌套哈希转换为扁平化结构。当前使用Ruby代码遍历sizes时:

parent['sizes'].each do |size|
  w: size['w'],
  h: size['h'],
  label: size
end

出现异常:label会加载整个哈希对象,而非对应的哈希标识字符串(如small、large),请问如何仅捕获哈希的标识字符串?

解决方法

在Ruby中遍历哈希时,each默认只传入值作为参数。如果要同时获取哈希的键(即你需要的标识字符串)和对应的值,有两种可行写法:

  1. 使用each_pair方法,明确接收键和值两个参数:
parent['sizes'].each_pair do |label, size|
  {
    w: size['w'],
    h: size['h'],
    label: label
  }
end
  1. 直接给each方法传入两个参数(键和值):
parent['sizes'].each do |label, size|
  {
    w: size['w'],
    h: size['h'],
    label: label
  }
end

两种写法都能让label变量拿到sizes哈希中的键(比如small、large),size则对应键的哈希值,这样就能正确提取宽高和标识字符串了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:41:12