本文介绍了什么是“Ruby的方式'来一次遍历两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比解决一个问题更的语法好奇...
我有长度相等的两个数组,并希望一次遍历他们两个 - 例如,同时输出他们在某一个指标值
。 @budget = [100,150,25,105]
@actual = [120,100,50,100]
我知道,我可以使用 each_index
键,索引,像这样的数组:
@ budget.each_index做|我|
把@budget [I]
把@actual [I]
结束
有没有的红宝石路的做到这一点更好?事情的如的吗?
#显然没有达到我希望它 - 但有没有这样的东西吗?
[@budget,@actual]。每做|预算,实际|
提出预算
把实际
结束
解决方案
>> @budget = [100,150,25,105]
= GT; [100,150,25,105]
>> @actual = [120,100,50,100]
= GT; [120,100,50,100]>> @ budget.zip @actual
= GT; [100,120],[150,100],[25,50],[105,100]]>> @ budget.zip(@actual)。每个做|预算,实际|
?>提出预算
>>把实际
>>结束
100
120
150
100
25
50
105
100
= GT; [100,120],[150,100],[25,50],[105,100]]
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 ]
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
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的方式'来一次遍历两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!