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

Ruby 2.15中使用each循环访问哈希元素报错,如何正确处理?

问题分析与修复方案

Hey there! Let's break down why you're hitting that TypeError and get your hash iteration working correctly.

First, let's recap your setup: you've got an outer hash test, where the key "foo" maps to an inner hash with id, lobbyist_id, and organization_id keys. The structure looks like this:

{ "foo" => { "id" => 5, "lobbyist_id" => 19, "organization_id" => 8 } }

The mistake here is how you're using each on the outer hash. In Ruby, when you call each on a hash, the block receives a two-element array representing each key-value pair (like ["foo", {"id"=>5, ...}] for your case). When you tried t["id"], you were treating that array like a hash—arrays only accept integer indices, hence the "no implicit conversion of String into Integer" error.

Correct Implementation Options

Here are two clean ways to access that id value properly:

Option 1: Explicitly capture key and value

This is the most readable approach—just split the key-value pair into separate variables in your block:

test.each do |key, inner_hash|
  puts inner_hash["id"]
end

Here, key will be "foo" (you can ignore it if you don't need it), and inner_hash is the actual hash containing the id you want. Accessing inner_hash["id"] will give you 5 as expected.

Option 2: Access the value via array index

If you prefer to keep a single block parameter, you can grab the value from the key-value array using index 1 (since index 0 is the key):

test.each do |key_value_pair|
  puts key_value_pair[1]["id"]
end

Quick note: The code you mentioned (test.each do |t| t.each do |t1| puts t1["id"] end end) won't work—because t is the key-value array, iterating over it will loop through "foo" (a string) and the inner hash. When it gets to "foo", trying t1["id"] will throw the same type error again.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:16:42