B
B
Bogdan2017-07-10 16:39:03
Ruby on Rails
Bogdan, 2017-07-10 16:39:03

Rails next array element?

Hello. It is necessary to form a new array and supplement the current element with the values ​​of the next element. If the element is the last, then the value of the next element will be the first element. Here is a working example, but it seems to me that it is not optimal, and can I write better? Thank you.

arr = [{id: 0, val: 'zero'}, {id: 1, val: 'one'}, {id: 2, val: 'two'}]
arr.map!.with_index { | v, i |
      next_v = arr[ arr.size == i + 1 ? 0 : i + 1 ];
      v.merge!( { next_id: next_v[ :id ], next_val: next_v[ :val ] } ) }

puts arr

# {id:0, val:"zero", next_id:1, next_val:"one"}
# {id:1, val:"one", next_id:2, next_val:"two"}
# {id:2, val:"two", next_id:0, next_val:"zero"}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SilentFl, 2017-07-20
@SilentFl

My version:

arr = [{id: 0, val: 'zero'}, {id: 1, val: 'one'}, {id: 2, val: 'two'}]
nexts = arr.rotate.map { |item| { next_id: item[:id], next_val: item[:val] } } # new hash with renamed keys
arr = arr.zip(nexts).map { |item, next_item| item.merge(next_item) }
puts arr

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question