93

Given I have an integer value of, e.g., 10.

How can I create an array of 10 elements like [1,2,3,4,5,6,7,8,9,10]?

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
Martin
  • 11,216
  • 23
  • 83
  • 140
  • 2
    Possible duplicate of [Correct way to populate an Array with a Range in Ruby](http://stackoverflow.com/questions/191329/correct-way-to-populate-an-array-with-a-range-in-ruby) – David Moles Mar 04 '16 at 17:58

6 Answers6

178

You can just splat a range:

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

Ruby 1.9 allows multiple splats, which is rather handy:

[*1..3, *?a..?c]
#=> [1, 2, 3, "a", "b", "c"]
Michael Kohl
  • 66,324
  • 14
  • 138
  • 158
  • 3
    This is great, because I didn't realised before that: [*0..0] #=> [0] But, [*1..0] #=> [] – hcarreras Apr 07 '16 at 08:18
  • @MichaelKohl - thank you - what does the question mark ? before the letters above signify? – BenKoshy Sep 23 '16 at 04:39
  • 2
    They are character literals. `?c == 'c' #=> true` – Michael Kohl Sep 23 '16 at 05:09
  • 1
    @MichaelKohl looks like a rather foreign approach, I think I'd prefer to use single quotes for clarity as in `[*1..3, *'a'..'z']` but this is great for code golfing and I also didn't know that `?a == 'a'` (maybe I'm missing more?), thumbs up :D – SidOfc Jan 30 '17 at 19:21
  • It may look foreign, but it's one of the literals Ruby supports. Others you may not be aware of are rationals `1/3r #=> (1/3)` and complex numbers `1 + 5i #=> (1+5i)` – Michael Kohl Jan 31 '17 at 04:39
  • 3
    I know you wrote this 7 years ago, but this is pretty cool. Thanks! – kevin Oct 15 '19 at 22:07
36

yet another tricky way:

> Array.new(10) {|i| i+1 }
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
10

About comments with tricky methods:

require 'benchmark'

Benchmark.bm { |x|
  x.report('[*..] ') do
    [*1000000 .. 9999999]
  end  

  x.report('(..).to_a') do
    (1000000 .. 9999999).to_a
  end

  x.report('Array(..)') do
    Array(1000000 .. 9999999)
  end

  x.report('Array.new(n, &:next)') do
    Array.new(8999999, &:next)
  end

}

Be careful, this tricky method Array.new(n, &:next) is slower while three other basic methods are same.

                           user     system      total        real
[*..]                  0.734000   0.110000   0.844000 (  0.843753)
(..).to_a              0.703000   0.062000   0.765000 (  0.843752)
Array(..)              0.750000   0.016000   0.766000 (  0.859374)
Array.new(n, &:next)   1.250000   0.000000   1.250000 (  1.250002)
Alexander.Iljushkin
  • 4,519
  • 7
  • 29
  • 46
9
def array_up_to(i)
    (1..i).to_a
end

Which allows you to:

 > array_up_to(10)
 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Darshan Rivka Whittle
  • 32,989
  • 7
  • 91
  • 109
3

You can do this:

array= Array(0..10)

If you want to input, you can use this:

puts "Input:"
n=gets.to_i
array= Array(0..n)
puts array.inspect
Sin Nguyen
  • 49
  • 1
  • 6
0

I think on of the most efficient way would be:

(1..10).to_a
Olivier Girardot
  • 389
  • 4
  • 16