简体   繁体   English

在Ruby数组中使用返回枚举器的方法的正确方法是什么?

[英]What is the proper way to use methods that return an enumerator in Ruby array?

Many methods in Ruby array return an enumerator when invoked without parameters or blocks ( index , keep_if , each , drop_while and many more). 在没有参数或块( indexkeep_ifeachdrop_while等等)的情况下调用时, Ruby数组中的许多方法都返回一个枚举器。

  • When is it appropriate to use methods in this form, as opposed to calling them with a block? 什么时候使用这种形式的方法,而不是用块调用它们?

From the docs to Enumerator : 从文档到Enumerator

Most methods have two forms: a block form where the contents are evaluated for each item in the enumeration, and a non-block form which returns a new Enumerator wrapping the iteration. 大多数方法都有两种形式:一种是块形式,其中内容是为枚举中的每个项目计算的,另一种是非块形式,它返回一个包含迭代的新枚举器。

This allows you to chain Enumerators together. 这允许您将枚举器链接在一起。 For example, you can map a list's elements to strings containing the index and the element as a string via: 例如,您可以将列表的元素映射到包含索引的字符串,并将元素映射为字符串,方法是:

 puts %w[foo bar baz].map.with_index {|w,i| "#{i}:#{w}" } # => ["0:foo", "1:bar", "2:baz"] 

An Enumerator can also be used as an external iterator. 枚举器也可以用作外部迭代器。 For example, Enumerator#next returns the next value of the iterator or raises StopIteration if the Enumerator is at the end. 例如,Enumerator#next返回迭代器的下一个值,或者如果Enumerator在结尾处则引发StopIteration。

 e = [1,2,3].each # returns an enumerator object. puts e.next # => 1 puts e.next # => 2 puts e.next # => 3 puts e.next # raises StopIteration 

I'm sorry for copy-paste, but I couldn't explain better. 我很抱歉复制粘贴,但我无法解释得更好。

The main original reason for the Enumerator class to exist is method chaining: Enumerator类存在的主要原因是方法链:

array.each.with_object [[], []] { |element, memo| ... }

So basically, you don't need to worry about that. 所以基本上,你不必担心这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Ruby on Rails:从方法返回数据的正确方法 - Ruby on Rails: proper way to return data from methods 在Rails 4控制器中调用方法的正确方法是什么? - What is the proper way to call methods in Rails 4 controllers? 安装Ruby gem的正确方法是什么? 使用RVM还是Bundler? - What is the proper way to install a Ruby gem; Using RVM or Bundler? 更新docker容器的Ruby bin文件夹的正确方法是什么? - What is the proper way to update the Ruby bin folder for a docker container? 使用React设计Ruby on Rails应用程序的正确方法是什么 - What's a proper way to design Ruby on Rails application with React 在Rails / Ruby中检查对象是否存在的正确方法是什么? - What is the proper way to check for existence of objects in Rails / Ruby? 在Ruby on Rails中访问虚拟属性的正确方法是什么? - What is the proper way to access virtual atributes in Ruby on Rails? 在 Ruby on Rails 中处理数据迁移的正确方法是什么? - What is the proper way of handling data migrations in Ruby on Rails? 并行运行Ruby脚本的正确方法是什么? - What's the proper way to run Ruby scripts in parallel? 在Ruby on Rails中处理地理区域设置的正确方法是什么? - What's the proper way to handle geographic locales in Ruby on Rails?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM