Skip to content

Instantly share code, notes, and snippets.

@glucero
Created October 16, 2012 14:53
Show Gist options
  • Save glucero/3899772 to your computer and use it in GitHub Desktop.
Save glucero/3899772 to your computer and use it in GitHub Desktop.
Starting with this array, how many different ways can you create two arrays of every other element
# 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
# 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
# 8 (pretty much the same thing as the one above)
collection = [Array.new, Array.new]
collection.map! { |a| a << array.shift } until array.empty?
# 9
array.values_at *array.each_index.select(&:even?)
array.values_at *array.each_index.select(&:odd?)
# 10 (slightly different than the one above)
array.each_index.select(&:even?).map { |i| array[i] }
array.each_index.select(&:odd?).map { |i| array[i] }
# 11
(0..(array.size - 1)).step(2).map { |i| array[i] }
(1..(array.size - 1)).step(2).map { |i| array[i] }
# 12 (pretty much the same thing as the one above)
2.times.map { |n| (n..(array.size - 1)).step(2).map { |i| array[i] } }
# 13 (weird, but my favorite)
collection = { true => [], false => [] }
array.each_index { |i| collection[i.even?] << array[i] }
collection.values
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment