簡體   English   中英

Ruby-更優雅地推向數組

[英]Ruby - more elegant pushing to array

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]]) }

最優雅的方法是什么?

使用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)

或使用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] }

在這種情況下,可以使用Enumerator對象:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM