當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby Enumerable.zip用法及代碼示例

本文簡要介紹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-lang.org大神的英文原創作品 Enumerable.zip。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。