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

This question is related to ruby arrays initialization

The answer is


To create such an array you could do:

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

You can do

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

As others have noted, you can also initialize an array with %w notation like so:

array = %w(1 2 3)

or

array = %w[1 2 3]

Please note that in both cases each element is a string, rather than an integer. So if you want an array whose elements are integers, you should not wrap each element with apostrophes:

array_of_integers = [1, 2, 3]

Also, you don't need to put comma in between the elements (which is necessary when creating an array without this %w notation). If you do this (which I often did by mistake), as in:

wrong_array = %w(1, 2, 3)

its elements will be three strings ---- "1,", "2,", "3". So if you do:

puts wrong_array

the output will be:

1,
2,
3
=>nil

which is not what we want here.

Hope this helps to clarify the point!


You can initialize an array in one step by writing the elements in [] like this:

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

To prove There's More Than One Six Ways To Do It:

plus_1 = 1.method(:+)
Array.new(3, &plus_1) # => [1, 2, 3]

If 1.method(:+) wasn't possible, you could also do

plus_1 = Proc.new {|n| n + 1}
Array.new(3, &plus_1) # => [1, 2, 3]

Sure, it's overkill in this scenario, but if plus_1 was a really long expression, you might want to put it on a separate line from the array creation.


Along with the above answers , you can do this too

    =>  [*'1'.."5"]   #remember *
    => ["1", "2", "3", "4", "5"]

Oneliner:

array = [] << 1 << 2 << 3   #this is for fixnums.

or

 a = %w| 1 2 3 4 5 |

or

 a = [*'1'..'3']

or

 a = Array.new(3, '1')

or

 a = Array[*'1'..'3']

You can simply do this with %w notation in ruby arrays.

array = %w(1 2 3)

It will add the array values 1,2,3 to the arrayand print out the output as ["1", "2", "3"]


If you have an Array of strings, you can also initialize it like this:

array = %w{1 2 3}

just separate each element with any whitespace


Examples related to ruby

Uninitialized Constant MessagesController Embed ruby within URL : Middleman Blog Titlecase all entries into a form_for text field Ruby - ignore "exit" in code Empty brackets '[]' appearing when using .where find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException) How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite? How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? How to update Ruby with Homebrew?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to initialization

"error: assignment to expression with array type error" when I assign a struct field (C) How to set default values in Go structs How to declare an ArrayList with values? Initialize array of strings Initializing a dictionary in python with a key value and no corresponding values Declare and Initialize String Array in VBA VBA (Excel) Initialize Entire Array without Looping Default values and initialization in Java Initializing array of structures C char array initialization