Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create array of n items based on integer value

Tags:

ruby

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

like image 880
Martin Avatar asked Jun 23 '12 21:06

Martin


People also ask

How do you create an array with N values?

To create an array with N elements containing the same value: Use the Array() constructor to create an array of N elements. Use the fill() method to fill the array with a specific value. The fill method changes all elements in the array to the supplied value.

Can we create a array having any number of values?

You can make an array of int s, double s, or any other type, but all the values in an array must have the same type. To create an array, you have to declare a variable with an array type and then create the array itself.

How can we create an array of 10 integers?

int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable. Java populates our array with default values depending on the element type - 0 for integers, false for booleans, null for objects, etc.


2 Answers

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"] 
like image 77
Michael Kohl Avatar answered Sep 20 '22 13:09

Michael Kohl


yet another tricky way:

> Array.new(10) {|i| i+1 } => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
like image 39
Dzmitry Plashchynski Avatar answered Sep 22 '22 13:09

Dzmitry Plashchynski