How can I get a list from a Ruby enumerable?

2020-04-09 22:09发布

问题:

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"]