2012-06-06 43 views
0
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

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

請你能解釋一下嗎? – Amias

+0

我無法解釋'Array#zip'更好[文檔](https://ruby-doc.org/core-2.2.0/Array.html#method-i-zip)。我希望['Array#map'](https://ruby-doc.org/core-2.2.0/Array.html#method-i-map)爲您所熟知。我不明白你爲什麼拒絕投票,但有你的解釋。 – Hauleth

+0

這裏的一般規則是你應該在你的回答中包括你的推理,而不是鏈接到可能改變的外部來源,這意味着你的回答是一個時間戳的解決方案。紅寶石文檔非常簡潔,我不覺得他們解釋了爲什麼zip更好。 – Amias

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

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

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