Benjamin
Benjamin

Reputation: 571

How to swap variables inside of a nested array?

I have 2 arrays that I've zipped together and now I'm trying to swipe values at even positions.

So this is what I've tried:

a = [1, 2, 3, 4]
b = [111, 222, 333, 444]
c = a.zip(b)

# Now c is equal to: [[1, 111], [2, 222],[3, 333],[4, 444]]

 c.map.with_index do |item, index|
   a = item[0]
   b = item[1]
   if index%2 == 0
     a, b = b, a
   end
 end

What I would like to have:

c = [[1, 111], [222,2], [3, 333],[444, 4]]

But it's still not working, is there a better solution ? Or how could I fix mine to make it work ?

EDIT: I've realized that I could probably just use the ".reverse" method to swap the element. But I still can't manage to make it work.

Upvotes: 0

Views: 109

Answers (2)

engineersmnky
engineersmnky

Reputation: 29318

I would probably go with

a = [1, 2, 3, 4]
b = [111, 222, 333, 444]

a.zip(b).each_with_index do |item, idx|
  item.reverse! if idx.odd?
end
#=>[[1, 111], [222, 2], [3, 333], [444, 4]] 

zip as you did and reverse! just the items where the index is odd.

Other options include:

a.map.with_index(1) do |item,idx| 
  [item].insert(idx % 2, b[idx -1])
end
#=>[[1, 111], [222, 2], [3, 333], [444, 4]] 

Here we use with_index starting with 1 and then use the modulo method to determine if the item in b should be placed at index 0 or index 1.

Or

a.zip(b).tap {|c| c.each_slice(2) {|_,b| b.reverse!}}
#=>[[1, 111], [222, 2], [3, 333], [444, 4]]

Here we zip a and b as your example did then we take the sub Arrays in groups of 2 and reverse the second Array using reverse! which will modify the Array in place.

Upvotes: 1

jvillian
jvillian

Reputation: 20263

Perhaps try:

c.map.with_index do |item, index|
  index%2 != 0 ? item.reverse : item
end

 => [[1, 111], [222, 2], [3, 333], [444, 4]] 

Upvotes: 3

Related Questions