如何从 Ruby 可枚举中获取列表?
我知道 Python 的 list
方法可以使用生成器中的所有元素。 Ruby 中有类似的东西吗?
我知道:
elements = []
enumerable.each {|i| elements << i}
我也知道 inject
替代方案。有现成可用的方法吗?
I know of Python's list
method that can consume all elements from a generator. Is there something like that available in Ruby?
I know of :
elements = []
enumerable.each {|i| elements << i}
I also know of the inject
alternative. Is there some ready available method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
枚举#to_a
Enumerable#to_a
如果您想对可枚举中的所有元素进行一些转换,#collect(又名#map)方法会很有帮助:
在此示例中,
elements
将包含中的所有元素>可枚举
,但每个都转换为字符串。例如,在本例中,
elements
将为['1', '2', '3']
。以下是 irb 的一些输出,说明了
each
和collect
之间的区别:If you want to do some transformation on all the elements in your enumerable, the #collect (a.k.a. #map) method would be helpful:
In this example,
elements
will contain all the elements that are inenumerable
, but with each of them translated to a string. E.g.In this case,
elements
would be['1', '2', '3']
.Here is some output from irb illustrating the difference between
each
andcollect
: