本文简要介绍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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。