Nate Beers
Nate Beers

Reputation: 1425

Remove elements from array, modify them, place them back in

i have an array of 16 digits:

 num = [1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8]

I have to take out all the digits starting with the second to last number counting back every other element to the first element:

 every_other_num = num.select.each_with_index{|key, value|value.even?}
 => [1,3,5,7,1,3,5,7]

Now, I need to double these digits:

 every_other_num_doubled = every_other_num.map {|num|num*2}
 => [2,6,10,14,2,6,10,14]

Then, I need to put them back into the original array in place of the ones I took out so the array would look like this:

 new_array = [2,2,6,4,10,6,14,8,2,2,6,4,10,6,14,8]

It is that last part I cant get. When I put them back in, I am getting a giant array because I am apparently not removing them from the old array. I am thinking the issue lies somewhere in the line of code every_other_num = num.select.each_with_index{|key, value|value.even?} because it isn't actually modifying the original array.

Upvotes: 0

Views: 87

Answers (4)

Cary Swoveland
Cary Swoveland

Reputation: 110755

num = [1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8]

even = false
num.map! { |e| (even=!even) ? 2*e : e }
  #=> [2, 2, 6, 4, 10, 6, 14, 8, 2, 2, 6, 4, 10, 6, 14, 8] 

Each element of num is passed into the block and doubled if its offset in num is even (multiple of 2) and left unchanged if it is odd. (even=!even) merely flips the value of even from true to false and from false to true. When the first element of num (at offset 0) is passed into the block, even is false, so it becomes true when (even=!even) is executed. That value is therefore doubled. When the second element of num (at offset 1) is passed to the block, even is flipped to false, so the value is left unchanged, and so on.

Upvotes: 0

pjs
pjs

Reputation: 19855

An alternative would be:

num.map!.with_index {|x,i| i.even? ? 2 * x : x}

Upvotes: 0

Kache
Kache

Reputation: 16737

You took your num array and made copies of the even indexed values, every_other_num.

You're right, the original array has not been modified.

Why not create yet another copy of num, that are the odd indexed values?

Upvotes: 0

user229044
user229044

Reputation: 239521

Why remove them? That makes no sense, there isn't really a reason I can see that being a requirement. Just double them in-place.

num.each_index { |i| nums[i] *= 2 if i.even? }

If you really want to remove/replace/re-insert, use zip/flatten to interweave the two arrays back together:

['a','b','c'].zip([1, 2, 3]).flatten
=> ["a", 1, "b", 2, "c", 3]

Upvotes: 3

Related Questions