0

In Python, we can use the list() method on an enumerable to create an ordered list based on the enumerator's items. How would you accomplish this in a Ruby enumerable?

This is currently what I'm using, but it feels a bit hack-ish:

data = []
e = # .. enumerable ..
e.each do |d|
  data << d
end
beakr
  • 5,709
  • 11
  • 42
  • 66

4 Answers4

1

You can do Array(list) :

(1..10).to_a #=> [1,2,3,4,5,6,7,8,9,10]

Same for other iterables

my_array.to_a
shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
1

try this out:--

e = # .. enumerable ..
e.to_a

or

e.entries
Sachin Singh
  • 7,107
  • 6
  • 40
  • 80
0

If you want to be clever, you could also play with several other enumerable methods. For example:

enumerable.map { | x | x }

enumerable.select { true }

...or my personal favorite,

enumerable.inject( [ ] ) { | c, i | c + [ i ] }
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
elreimundo
  • 6,186
  • 1
  • 13
  • 6
0

In Python list("a") results in a list; in Ruby "a".to_a gives an error. The splat operator called an an 'unsplattableobject results in the object itself. So maybe this is more equivalent to Pythonslist`:

a = ("a".."f").each_cons(2)
[*a] #=> [["a", "b"], ["b", "c"], ["c", "d"], ["d", "e"], ["e", "f"]]

[*"a"] #=> ["a"]
steenslag
  • 79,051
  • 16
  • 138
  • 171