user1293367
user1293367

Reputation: 19

How to multiply every other element of an array?

Let's say that I have an array like this:

[1,2,3,4,5,6,7]

how can I multiply every other number of this array except the first by 2 so my new array looks like this

[1,4,3,8,5,12,7]

Upvotes: 1

Views: 1851

Answers (2)

sawa
sawa

Reputation: 168101

[1,2,3,4,5,6,7].each_slice(2).flat_map{|k, l| [k, *(l * 2 if l)]}
# => [1, 4, 3, 8, 5, 12, 7]

Upvotes: 1

valodzka
valodzka

Reputation: 5805

You can use map and with_index:

[1,2,3,4,5,6,7].map.with_index{|v,i| i % 2 == 0 ? v : v * 2 } 
# => [1, 4, 3, 8, 5, 12, 7]

Upvotes: 4

Related Questions