Last Updated: February 25, 2016
·
2.443K
· glucero

Creating two arrays from alternating elements of another array.

Starting with this array, how many different ways can you create two arrays of every other element:

array = %w(key_a value_a key_b value_b key_c value_c)

1

hash = Hash[*array]
hash.keys
hash.values

2

Hash[*array].to_a.transpose

2b (Hash[] accepts a zipped array as well as a sequence of arguments.)

Hash[array.each_slice(2).to_a].to_a.transpose

3

array.each_slice(2).to_a.transpose

4

array.partition { |v| array.index(v).even? }

5

keys = []
values = []
array.each_slice(2) do |key, value|
  keys << key
  values << value
end

6

keys = []
values = []
array.each_index do |index|
  if index.even?
    keys << array[index]
  else
    values << array[index]
  end
end

7

keys = []
values = []
until array.empty?
  keys << array.shift
  values << array.shift
end

7b (pretty much the same thing as the one above)

collection = [Array.new, Array.new]
collection.map! { |a| a << array.shift } until array.empty?

8

array.values_at *array.each_index.select(&:even?)
array.values_at *array.each_index.select(&:odd?)

9 (slightly different than the one above)

array.each_index.select(&:even?).map { |i| array[i] }
array.each_index.select(&:odd?).map { |i| array[i] }

10

(0..(array.size - 1)).step(2).map { |i| array[i] }
(1..(array.size - 1)).step(2).map { |i| array[i] }

10b (pretty much the same thing as the one above)

2.times.map do |n|
  (n..(array.size - 1)).step(2).map { |i| array[i] }
end

11 (a little weird)

collection = { true => [], false => [] }
array.each_index { |i| collection[i.even?] << array[i] }
collection.values

Did I miss anything?

1 Response
Add your response

array.reduce [[],[]] do |memo, value|
  memo.first << value
  memo.reverse
end
over 1 year ago ·