How to initialize an array in one step using Ruby?
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]
Along with the above answers , you can do this too
=> [*'1'.."5"] #remember *
=> ["1", "2", "3", "4", "5"]
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.
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']