I have an array like this:
array = ['1','a','2','b']
I want to make it like this:
['x', '1', 'y', 'a', 'x', '2', 'y', 'b']
I tried for many hours but has no result. My best attempt was:
a = array.each_with_index do |val, index|
case index
when index == 0
a.insert(index, 'x')
when index.odd?
a.insert(index, 'x')
when index.even?
a.insert(index, 'y')
end
end
You could do something like this, using methods from the Enumerable module:
ary = ['1', 'a', '2', 'b']
xy = ['x', 'y']
ary.zip(xy.cycle)
# => [["1", "x"], ["a", "y"], ["2", "x"], ["b", "y"]]
ary.zip(xy.cycle).flat_map(&:reverse)
# => ["x", "1", "y", "a", "x", "2", "y", "b"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With