1

I'm new at Ruby, and failing to Google this easy question:

What's the normal way to obtain a list of numbers [1, 2, ..., n] in Ruby? In Haskell I just type [1..n], and I'm sure that this is easy in Ruby also, but I can't guess it.

Eric Wilson
  • 57,719
  • 77
  • 200
  • 270

4 Answers4

14

1..n is a Range in Ruby. You can convert it to an array using (1..n).to_a or the shorter form [*1..n].

Depending on what you're doing, using the Range directly might be more efficient.

Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • +1 for `[*1..n]`. Do you have a link that explains why it works? I've been looking for that, and `&` too, for quite a while, but I simply can't find a description of those features. – Matheus Moreira Apr 08 '11 at 16:19
  • It's called the Splat operator. More info: http://theplana.wordpress.com/2007/03/03/ruby-idioms-the-splat-operator/ and http://stackoverflow.com/questions/776462/where-is-it-legal-to-use-ruby-splat-operator – Dogbert Apr 08 '11 at 16:31
3

Ruby has special range objects, written as 1..10 or whatever. For many purposes you can use one of these instead of an array. If you need the array, call the range object's to_a method:

(1..10).to_a
Gareth McCaughan
  • 19,888
  • 1
  • 41
  • 62
1

You mean a range? You can do it like this:

(0..n)

This will give you an array that has the numbers 0 to 9 in it.

For more information about ranges and arrays, visit here: http://www.ruby-doc.org/core/classes/Range.html

alexyorke
  • 4,224
  • 3
  • 34
  • 55
1

Another approach is

1.upto(9).to_a

Pretty boring by itself, but you can also do

1.step(10, 3).to_a #=> [1, 4, 7, 10]
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338