You can do
array = ['1', '2', '3']
As others noted, you can also initialize the array with the designation% w as follows:
array = %w(1 2 3)
or
array = %w[1 2 3]
Note that in both cases, each element is a string, not an integer. Therefore, if you want an array whose elements are integers, you should not wrap each element with apostrophes:
array_of_integers = [1, 2, 3]
In addition, you do not need to enter a comma 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 consist of three lines: "1", "2", "3". So if you do this:
puts wrong_array
the output will be:
1, 2, 3 =>nil
what we do not want here.
Hope this helps clarify the point!
John Titor Mar 08 '16 at 21:51 2016-03-08 21:51
source share