Create an array of n elements based on an integer value

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

How to create an array of 10 elements, such as [1,2,3,4,5,6,7,8,9,10] ?

+42
ruby
Jun 23 2018-12-12T00:
source share
5 answers

You can simply select a range:

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

Ruby 1.9 allows you to use several combinations, which is quite convenient:

 [*1..3, *?a..?c] #=> [1, 2, 3, "a", "b", "c"] 
+93
Jun 23 2018-12-12T00:
source share

another tricky way:

 > Array.new(10) {|i| i+1 } => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
+16
Jun 23 '12 at 22:22
source share
 def array_up_to(i) (1..i).to_a end 

What allow:

  > array_up_to(10) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
+6
Jun 23 2018-12-12T00:
source share

About comments using sophisticated 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 complex Array.new(n, &:next) method is slower, while the other three base methods are the 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) 
+5
Dec 14 '15 at 0:25
source share

You can do it:

 array= Array(0..10) 

If you want to enter, you can use this:

 puts "Input:" n=gets.to_i array= Array(0..n) puts array.inspect 
+1
Nov 08 '14 at 2:39
source share



All Articles