ruby method returns wrong elements with odd/even index ruby 2.6.0

Viewed 97
def even_odd_array
  number = 5169294814153321
  array_odd_index = []
  array_even_index = []

  array_of_chars = number.to_s.chars.map(&:to_i)
  array_of_chars.each { |x| array_of_chars.index(x) % 2 == 0 ? array_even_index << x : array_odd_index << x } <----- this returns wrong arrays
  #array_odd_index, array_even_index = array_of_chars.each_slice(2).to_a.transpose
  p array_even_index
  p array_odd_index  
end

array_even_index [5, 6, 2, 4, 4, 5, 3, 3, 2]

array_odd_index [1, 9, 9, 8, 1, 1, 1]

what's wrong with it and are there any other ways to make it?

1 Answers

The problem with your actual code is that index returns the index of the first element it finds in the receiver. As 1 is 4 times in number it'll return the index of the first 1 in number from left to right, same for all other repeated numbers.

An easy solution; use each_with_index which allows you to iterate over each element in the receiver plus yielding the current index of that element, so you can check if the index is even or not, deciding where to push the element:

array_of_chars.each_with_index do |x, index|
  if index.even?
    array_even_index << x
  else
    array_odd_index << x
  end
end

Or you can use partition plus with_index for that:

array_even_index, array_odd_index = 5169294814153321.digits.reverse.partition.with_index { |_, index| index.even? }
p array_even_index # [5, 6, 2, 4, 1, 1, 3, 2]
p array_odd_index # [1, 9, 9, 8, 4, 5, 3, 1]
Related