Ruby - 更优雅推送到阵列

时间:2012-06-06 13:13:01

标签: ruby-on-rails arrays append each

valrow = [ 0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
lblrow = [48,  8539,  188,  8540, 189,  8541,  190,  8542]
opts = []
(0..7).each {|i| opts.push([lblrow[i].chr(Encoding::UTF_8), valrow[i]]) }

最优雅的方法是什么?

3 个答案:

答案 0 :(得分:3)

使用Array#zip

valrow = [ 0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
lblrow = [48,  8539,  188,  8540, 189,  8541,  190,  8542]
opts = lblrow.map { |c| c.chr(Encoding::UTF_8) }.zip(valrow)

答案 1 :(得分:1)

或使用collect.with_index

valrow = [ 0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
lblrow = [48,  8539,  188,  8540, 189,  8541,  190,  8542]
opts = valrow.collect.with_index { |val,index| [lblrow[index].chr(Encoding::UTF_8), val] }

答案 2 :(得分:1)

在这种情况下,您可以使用Enumerator对象:

value_enum = valrow.to_enum
opts = lblrow.map { |item| [item.chr(Encoding::UTF_8), value_enum.next] }