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

在Ruby块中使用with_index时如何实现数组解构?

在Ruby中结合with_index实现数组解构

当你使用each.with_index时,Ruby会把每次迭代的元素和索引作为两个独立参数传递给块,这直接导致你原来的解构写法失效。要同时实现解构和获取索引,只需把解构的数组用括号包裹,作为块的第一个参数,索引作为第二个参数。

正确写法:

[ [ 1, 2 ], [ 3, 4 ] ].each.with_index do |(first, second), index|
  puts second
end
#=> 2
#=> 4

原因说明:

  • 不带with_index时,each只传递子数组给块,Ruby会自动解构|first, second|的参数。
  • 加上with_index后,块的参数变成了「子数组 + 索引」的组合。此时用(first, second)包裹,就是明确告诉Ruby:把第一个块参数(子数组)解构为first和second,第二个块参数是迭代的索引index。

扩展示例(同时使用索引和解构元素):

[ [ 1, 2 ], [ 3, 4 ] ].each.with_index do |(first, second), index|
  puts "第#{index+1}个元素对:first=#{first}, second=#{second}"
end
#=> 第1个元素对:first=1, second=2
#=> 第2个元素对:first=3, second=4

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 10:55:59