Create array of n items based on integer value

Ruby

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

yet another tricky way:

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

Solution 3 - Ruby

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)

Solution 4 - Ruby

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]

Solution 5 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartinView Question on Stackoverflow
Solution 1 - RubyMichael KohlView Answer on Stackoverflow
Solution 2 - RubyDzmitry PlashchynskiView Answer on Stackoverflow
Solution 3 - RubyAlexander.IljushkinView Answer on Stackoverflow
Solution 4 - RubyDarshan Rivka WhittleView Answer on Stackoverflow
Solution 5 - RubySin NguyenView Answer on Stackoverflow