Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby array creation, Array.new vs []

What's the difference between these two statements? I use them in my rails app and to me it looks like they do the same thing

array_a = Array.new array_b = [] 
like image 777
Lan Avatar asked Jan 05 '11 07:01

Lan


People also ask

What is array new in Ruby?

A new array can be created by using the literal constructor [] . Arrays can contain different types of objects. For example, the array below contains an Integer , a String and a Float: ary = [1, "two", 3.0] #=> [1, "two", 3.0] An array can also be created by explicitly calling Array.

How do you create 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.


1 Answers

Those two statements are functionally identical. Array.new however can take arguments and a block:

Array.new # => [] Array.new(2) # => [nil,nil] Array.new(5,"A") # =>["A","A","A","A","A"]  a = Array.new(2,Hash.new) a[0]['cat'] = 'feline' a # => [{"cat"=>"feline"},{"cat"=>"feline"}] a[1]['cat'] = 'Felix' a # => [{"cat"=>"Felix"},{"cat"=>"Felix"}]  a = Array.new(2){Hash.new} # Multiple instances a[0]['cat'] = 'feline' a # =>[{"cat"=>"feline"},{}] squares = Array.new(5){|i|i*i} squares # => [0,1,4,9,16]  copy = Array.new(squares) # initialized by copying squares[5] = 25 squares # => [0,1,4,9,16,25] copy # => [0,1,4,9,16] 

Note: the above examples taken from Programming Ruby 1.9

like image 169
zetetic Avatar answered Sep 28 '22 17:09

zetetic