ruby - Multiply even-indexed elements of array by 2 and odd-indexed elements of array by 3? -
i have following array contains numbers 1 10:
numbers = [1,2,3,4,5,6,7,8,9,10]
i want multiply every even-indexed element 2 , every odd-indexed element 3. want array like:
[2,6,6,12,10,18,14,24,18,30]
i tried following solution:
numbers.select |x| if x.even? x * 2 else x * 3 end puts x end
unfortunately, didn't work. have better methods?
looks want every index multiplied 2, , odd indices 3.
this should trick
numbers = [1,2,3,4,5,6,7,8,9,10] numbers.map!.with_index { |n, i| i.even? ? n * 2 : n * 3 } p numbers # => [2,6,6,12,10,18,14,24,18,30]
as attempt, #select
selects elements enumerator wherever result of block true. when want modify enumerator in place, should use #map!
. #with_index
method available enumerators include index in block.
Comments
Post a Comment