How can I get a list from a Ruby enumerable?

北战南征 提交于 2019-12-19 21:41:23

问题


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?


回答1:


Enumerable#to_a




回答2:


If you want to do some transformation on all the elements in your enumerable, the #collect (a.k.a. #map) method would be helpful:

elements = enumerable.collect { |item| item.to_s }

In this example, elements will contain all the elements that are in enumerable, but with each of them translated to a string. E.g.

enumerable = [1, 2, 3]
elements = enumerable.collect { |number| number.to_s }

In this case, elements would be ['1', '2', '3'].

Here is some output from irb illustrating the difference between each and collect:

irb(main):001:0> enumerable = [1, 2, 3]
=> [1, 2, 3]
irb(main):002:0> elements = enumerable.each { |number| number.to_s }
=> [1, 2, 3]
irb(main):003:0> elements
=> [1, 2, 3]
irb(main):004:0> elements = enumerable.collect { |number| number.to_s }
=> ["1", "2", "3"]
irb(main):005:0> elements
=> ["1", "2", "3"]


来源:https://stackoverflow.com/questions/1395652/how-can-i-get-a-list-from-a-ruby-enumerable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!