Paul
Paul

Reputation: 26690

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

What is the most elegant way to do this?

Upvotes: 0

Views: 179

Answers (3)

Hauleth
Hauleth

Reputation: 23586

Use 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)

Upvotes: 3

Christoph Petschnig
Christoph Petschnig

Reputation: 4157

You can use an Enumerator object in this case:

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

Upvotes: 1

Tigraine
Tigraine

Reputation: 23678

Or use 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] }

Upvotes: 1

Related Questions