当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Enumerator.with_object用法及代码示例


本文简要介绍ruby语言中 Enumerator.with_object 的用法。

用法

with_object(obj) {|(*args), obj| ... }
with_object(obj)

使用任意对象 obj 迭代每个元素的给定块,并返回 obj

如果没有给出块,则返回一个新的 Enumerator

示例

to_three = Enumerator.new do |y|
  3.times do |x|
    y << x
  end
end

to_three_with_string = to_three.with_object("foo")
to_three_with_string.each do |x,string|
  puts "#{string}: #{x}"
end

# => foo: 0
# => foo: 1
# => foo: 2

相关用法


注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Enumerator.with_object。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。