Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an array in one step using Ruby?

I initialize an array this way:

array = Array.new array << '1' << '2' << '3' 

Is it possible to do that in one step? If so, how?

like image 318
user502052 Avatar asked Feb 05 '11 17:02

user502052


People also ask

How do you initialize an empty array in Ruby?

You can create an empty array by creating a new Array object and storing it in a variable. This array will be empty; you must fill it with other variables to use it. This is a common way to create variables if you were to read a list of things from the keyboard or from a file.

How do you assign an array in Ruby?

To update an element in the array, assign a new value to the element's index by using the assignment operator, just like you would with a regular variable. To make sure you update the right element, you could use the index method to locate the element first, just like you did to find the element you wanted to delete.

How do you initialize an array?

To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15}; Or, you could generate a stream of values and assign it back to the array: int[] intArray = IntStream.


1 Answers

You can use an array literal:

array = [ '1', '2', '3' ] 

You can also use a range:

array = ('1'..'3').to_a  # parentheses are required # or array = *('1'..'3')      # parentheses not required, but included for clarity 

For arrays of whitespace-delimited strings, you can use Percent String syntax:

array = %w[ 1 2 3 ] 

You can also pass a block to Array.new to determine what the value for each entry will be:

array = Array.new(3) { |i| (i+1).to_s } 

Finally, although it doesn't produce the same array of three strings as the other answers above, note also that you can use enumerators in Ruby 1.8.7+ to create arrays; for example:

array = 1.step(17,3).to_a #=> [1, 4, 7, 10, 13, 16] 
like image 80
Phrogz Avatar answered Oct 26 '22 10:10

Phrogz