Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat a sequence and interleave it with an array

Tags:

ruby

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
like image 944
Michael Karavaev Avatar asked Dec 01 '25 03:12

Michael Karavaev


1 Answers

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"]
like image 157
toro2k Avatar answered Dec 03 '25 19:12

toro2k