本文簡要介紹ruby語言中 Array.zip
的用法。
用法
zip(*other_arrays) → new_array
zip(*other_arrays) {|other_array| ... } → nil
當沒有給出塊時,返回一個大小為self.size
的新數組new_array
,其元素是數組。
每個嵌套數組 new_array[n]
的大小為 other_arrays.size+1
,並包含:
-
self
的nth
元素。 -
每個
other_arrays
的nth
元素。
如果所有 other_arrays
和 self
的大小相同:
a = [:a0, :a1, :a2, :a3]
b = [:b0, :b1, :b2, :b3]
c = [:c0, :c1, :c2, :c3]
d = a.zip(b, c)
d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, :c2], [:a3, :b3, :c3]]
如果 other_arrays
中的任何數組小於 self
,則使用 nil
填充到 self.size
:
a = [:a0, :a1, :a2, :a3]
b = [:b0, :b1, :b2]
c = [:c0, :c1]
d = a.zip(b, c)
d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, nil], [:a3, nil, nil]]
如果 other_arrays
中的任何數組大於 self
,則忽略其尾隨元素:
a = [:a0, :a1, :a2, :a3]
b = [:b0, :b1, :b2, :b3, :b4]
c = [:c0, :c1, :c2, :c3, :c4, :c5]
d = a.zip(b, c)
d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, :c2], [:a3, :b3, :c3]]
當給定一個塊時,用每個子數組(如上形成)調用該塊;返回零
a = [:a0, :a1, :a2, :a3]
b = [:b0, :b1, :b2, :b3]
c = [:c0, :c1, :c2, :c3]
a.zip(b, c) {|sub_array| p sub_array} # => nil
輸出:
[:a0, :b0, :c0]
[:a1, :b1, :c1]
[:a2, :b2, :c2]
[:a3, :b3, :c3]
相關用法
- Ruby Array.zip()用法及代碼示例
- Ruby Array.push用法及代碼示例
- Ruby Array.hash用法及代碼示例
- Ruby Array.to_a用法及代碼示例
- Ruby Array.to_h用法及代碼示例
- Ruby Array.to_s用法及代碼示例
- Ruby Array.array + other_array用法及代碼示例
- Ruby Array.take()用法及代碼示例
- Ruby Array.reject!用法及代碼示例
- Ruby Array.flatten!用法及代碼示例
- Ruby Array.reject用法及代碼示例
- Ruby Array.repeated_permutation()用法及代碼示例
- Ruby Array.index()用法及代碼示例
- Ruby Array.pack()用法及代碼示例
- Ruby Array.rassoc(obj)用法及代碼示例
- Ruby Array.values_at()用法及代碼示例
- Ruby Array.each用法及代碼示例
- Ruby Array.fetch用法及代碼示例
- Ruby Array.flatten用法及代碼示例
- Ruby Array.sort用法及代碼示例
- Ruby Array.unshift()用法及代碼示例
- Ruby Array.reverse用法及代碼示例
- Ruby Array.array | other_array用法及代碼示例
- Ruby Array.rotate()用法及代碼示例
- Ruby Array.rindex用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Array.zip。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。