一次迭代两个数组的“Ruby 方式"是什么 [英] What's the 'Ruby way' to iterate over two arrays at once

查看:29
本文介绍了一次迭代两个数组的“Ruby 方式"是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与其说是解决问题,不如说是对语法的好奇……

More of a syntax curiosity than a problem to solve...

我有两个长度相等的数组,我想同时对它们进行迭代 - 例如,在某个索引处输出它们的值.

I have two arrays of equal length, and want to iterate over them both at once - for example, to output both their values at a certain index.

@budget = [ 100, 150, 25, 105 ]
@actual = [ 120, 100, 50, 100 ]

我知道我可以像这样使用 each_index 和索引到数组中:

I know that I can use each_index and index into the arrays like so:

@budget.each_index do |i|
  puts @budget[i]
  puts @actual[i]
end

有没有 Ruby 方法 可以做得更好?什么这样的?

Is there a Ruby way to do this better? Something like this?

# Obviously doesn't achieve what I want it to - but is there something like this?
[@budget, @actual].each do |budget, actual|
  puts budget
  puts actual
end

推荐答案

>> @budget = [ 100, 150, 25, 105 ]
=> [100, 150, 25, 105]
>> @actual = [ 120, 100, 50, 100 ]
=> [120, 100, 50, 100]

>> @budget.zip @actual
=> [[100, 120], [150, 100], [25, 50], [105, 100]]

>> @budget.zip(@actual).each do |budget, actual|
?>   puts budget
>>   puts actual
>> end
100
120
150
100
25
50
105
100
=> [[100, 120], [150, 100], [25, 50], [105, 100]]

这篇关于一次迭代两个数组的“Ruby 方式"是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆