在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
相关产品推荐
相关产品推荐

