On Mon, Dec 12, 2011 at 11:31 AM, Janko Muzykant <umrzykus / gazeta.pl> wrote=
:
> As far as I know, I can create Arrays and Hashes in Ruby at least in two
> ways, either by:
>
> =A0 =A0 =A0 =A0a =3D []
> or by:
> =A0 =A0 =A0 =A0a =3D Array.new
>
> I'm coming from JavaScript world and in JS the first form is prefered ove=
r
> 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:
>
> =A0 =A0 =A0 =A0a =3D ["Ala", "ma", "kota"]

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

a =3D %w{Ala ma kota}
a =3D %w[Ala ma kota]
a =3D %w(Ala ma kota)
a =3D %w<Ala ma kota>

etc.

> but on the other hand, for empty array with element added dynamically
> later, following form is more accurate:
>
> =A0 =A0 =A0 =A0a =3D Array.new =A0 # not a =3D []
> =A0 =A0 =A0 =A0a.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 =3D Array.new 5, 0
=3D> [0, 0, 0, 0, 0]
irb(main):004:0> a =3D Array.new(5) {|i| "dat #{i}"}
=3D> ["dat 0", "dat 1", "dat 2", "dat 3", "dat 4"]

and for Hash

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

as well as

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

Kind regards

robert


--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/