如何2個陣列組合這樣如何提取的陣列的元件,並且在另一個插入它,而仍保留其原始索引
a = ["x","y","z"]
b = [["a","b"],["c","d"],["e","f"]]
預期輸出:
[["a","b","x" ],["c","d","y"],["e","f","z"]]
是否有任何內在的方法?
如何2個陣列組合這樣如何提取的陣列的元件,並且在另一個插入它,而仍保留其原始索引
a = ["x","y","z"]
b = [["a","b"],["c","d"],["e","f"]]
預期輸出:
[["a","b","x" ],["c","d","y"],["e","f","z"]]
是否有任何內在的方法?
有。您可以結合使用Array#zip
與Array#flatten
:
b.zip(a).map(&:flatten)
#=> [["a", "b", "x"], ["c", "d", "y"], ["e", "f", "z"]]
另一種方式是:
[b, a].transpose.map(&:flatten)
#=> [["a", "b", "x"], ["c", "d", "y"], ["e", "f", "z"]]
:)
這裏是這樣做另一種方式:
a = ["x","y","z"]
b = [["a","b"],["c","d"],["e","f"]]
b.map.with_index {|arr, idx| arr << a[idx]}
#=> [["a", "b", "x"], ["c", "d", "y"], ["e", "f", "z"]]
enum = a.to_enum
b.map { |arr| arr << enum.next }
#=> [["a", "b", "x"], ["c", "d", "y"], ["e", "f", "z"]]