本文簡要介紹ruby語言中 Enumerable.zip
的用法。
用法
zip(*other_enums) → array
zip(*other_enums) {|array| ... } → nil
在沒有給出塊的情況下,返回一個大小為 self.size 的新數組 new_array
,其元素是數組。每個嵌套數組 new_array[n]
的大小為 other_enums.size+1
,並包含:
-
n
-self 的第一個元素。 -
n
每個other_enums
的第一個元素。
如果所有 other_enums
和 self 大小相同,則所有元素都包含在結果中,並且沒有 nil
-填充:
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]]
f = {foo: 0, bar: 1, baz: 2}
g = {goo: 3, gar: 4, gaz: 5}
h = {hoo: 6, har: 7, haz: 8}
d = f.zip(g, h)
d # => [
# [[:foo, 0], [:goo, 3], [:hoo, 6]],
# [[:bar, 1], [:gar, 4], [:har, 7]],
# [[:baz, 2], [:gaz, 5], [:haz, 8]]
# ]
如果 other_enums 中的任何可枚舉項小於自身,則使用 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_enums 中的任何可枚舉大於 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 Enumerable.any?用法及代碼示例
- Ruby Enumerable.slice_before用法及代碼示例
- Ruby Enumerable.uniq用法及代碼示例
- Ruby Enumerable.find_all用法及代碼示例
- Ruby Enumerable.max用法及代碼示例
- Ruby Enumerable.map用法及代碼示例
- Ruby Enumerable.min_by用法及代碼示例
- Ruby Enumerable.find_index用法及代碼示例
- Ruby Enumerable.minmax用法及代碼示例
- Ruby Enumerable.drop用法及代碼示例
- Ruby Enumerable.member?用法及代碼示例
- Ruby Enumerable.each_cons用法及代碼示例
- Ruby Enumerable.entries用法及代碼示例
- Ruby Enumerable.flat_map用法及代碼示例
- Ruby Enumerable.reject用法及代碼示例
- Ruby Enumerable.each_with_index用法及代碼示例
- Ruby Enumerable.filter_map用法及代碼示例
- Ruby Enumerable.sort用法及代碼示例
- Ruby Enumerable.all?用法及代碼示例
- Ruby Enumerable.take用法及代碼示例
- Ruby Enumerable.reduce用法及代碼示例
- Ruby Enumerable.each_with_object用法及代碼示例
- Ruby Enumerable.sort_by用法及代碼示例
- Ruby Enumerable.one?用法及代碼示例
- Ruby Enumerable.sum用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Enumerable.zip。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。