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
3 个解决方案
#1
5
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"]
#2
1
Also any of these ways will work
而且,这些方法中的任何一种都会起作用
array = ['1','a','2','b']
array.each_slice(2).map {|a| ['x','y'].zip(a)}.flatten.compact
#=>["x", "1", "y", "a", "x", "2", "y", "b"]
(['x','y'] * (array.size / 2.0).ceil).take(array.size).zip(array).flatten
#=>["x", "1", "y", "a", "x", "2", "y", "b"]
array.each_slice(2).flat_map {|a| ['x','y'].zip(a).flatten}.compact
#=>["x", "1", "y", "a", "x", "2", "y", "b"]
['x','y'].cycle(array.size / 2 + array.size % 2).take(array.size).zip(array).flatten
#=>["x", "1", "y", "a", "x", "2", "y", "b"]
#3
0
This might help:
这可能帮助:
array.zip(['x', 'y'].cycle).map(&:reverse).flatten(1) #=> ["x", "1", "y", "a", "x", "2", "y", "b"]
#1
5
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"]
#2
1
Also any of these ways will work
而且,这些方法中的任何一种都会起作用
array = ['1','a','2','b']
array.each_slice(2).map {|a| ['x','y'].zip(a)}.flatten.compact
#=>["x", "1", "y", "a", "x", "2", "y", "b"]
(['x','y'] * (array.size / 2.0).ceil).take(array.size).zip(array).flatten
#=>["x", "1", "y", "a", "x", "2", "y", "b"]
array.each_slice(2).flat_map {|a| ['x','y'].zip(a).flatten}.compact
#=>["x", "1", "y", "a", "x", "2", "y", "b"]
['x','y'].cycle(array.size / 2 + array.size % 2).take(array.size).zip(array).flatten
#=>["x", "1", "y", "a", "x", "2", "y", "b"]
#3
0
This might help:
这可能帮助:
array.zip(['x', 'y'].cycle).map(&:reverse).flatten(1) #=> ["x", "1", "y", "a", "x", "2", "y", "b"]