How to create Arrays (and Hashes) correctly?

hi,
As far as I know, I can create Arrays and Hashes in Ruby at least in two
ways, either by:

    a = []

or by:
a = Array.new

I’m coming from JavaScript world and in JS the first form is prefered
over
the second one. Is there any difference in Arrays (and Hashes) created
in
Ruby by [] (and {} respectively) and Array.new (Hash.new) ?

I tried to answer myself searching in google and the only conclusion I
found is that, when creating arrays with elements, one should use:

    a = ["Ala", "ma", "kota"]

but on the other hand, for empty array with element added dynamically
later, following form is more accurate:

    a = Array.new   # not a = []
    a.push(...)

Is that right, or have I misunderstood something here?

thanks,
jm.

On Mon, Dec 12, 2011 at 11:31 AM, Janko M. [email protected]
wrote:

As far as I know, I can create Arrays and Hashes in Ruby at least in two
ways, either by:

a = []
or by:
a = Array.new

I’m coming from JavaScript world and in JS the first form is prefered over
the second one. Is there any difference in Arrays (and Hashes) created in
Ruby by [] (and {} respectively) and Array.new (Hash.new) ?

No, if you only consider constructor without arguments. But
constructors with arguments provide additional features (see
documentation).

I tried to answer myself searching in google and the only conclusion I
found is that, when creating arrays with elements, one should use:

a = [“Ala”, “ma”, “kota”]

For strings you can even do this if they do not contain whitespace:

a = %w{Ala ma kota}
a = %w[Ala ma kota]
a = %w(Ala ma kota)
a = %w

etc.

but on the other hand, for empty array with element added dynamically
later, following form is more accurate:

a = Array.new # not a = []
a.push(…)

Is that right, or have I misunderstood something here?

I prefer to use [] over Array.new and {} over Hash.new as it is less
typing and visually more obvious. I only resort to Array.new and
Hash.new if I need functionality with the constructor, e.g.

irb(main):003:0> a = Array.new 5, 0
=> [0, 0, 0, 0, 0]
irb(main):004:0> a = Array.new(5) {|i| “dat #{i}”}
=> [“dat 0”, “dat 1”, “dat 2”, “dat 3”, “dat 4”]

and for Hash

irb(main):005:0> h = Hash.new 0
=> {}
irb(main):006:0> h[:x] += 1
=> 1
irb(main):007:0> h
=> {:x=>1}

as well as

irb(main):008:0> h = Hash.new {|ha,k| ha[k] = []}
=> {}
irb(main):009:0> h[:y] << “foo”
=> [“foo”]
irb(main):010:0> h[:y] << “bar”
=> [“foo”, “bar”]
irb(main):011:0> h[:x] << 123
=> [123]
irb(main):012:0> h
=> {:y=>[“foo”, “bar”], :x=>[123]}

Kind regards

robert