Ruby Interview Questions

Displaying 1 - 10 of 27

Ruby program to partition in 2 arrays one with even and another with odd

Write an evens_and_odds method that accepts an array of whole numbers. It should return an array of 2 arrays:

  • The first nested array should contain only the odd numbers.
  • The second nested array should contain only the even numbers.

If there are no even or odd numbers, the respective inner array should be empty.

Example:

evens_and_odds([2, 4, 8, 15, 16, 23, 42])
Output: [[15,23], [2, 4, 8, 16, 42]]

evens_and_odds([2, 4, 6, 8])
Output: [[], [2, 4, 6 , 8]]

evens_and_odss([1, 3, 5])
Output: [[1, 3, 5], []]

Code:

def evens_and_odds(numbers)
  numbers.partition{|x| x.odd?}
end

evens_and_odds([2, 4, 8, 15, 16, 23, 42])
evens_and_odds([2, 4, 6, 8])
evens_and_odds([1, 3, 5])