Let’s Make An [Array] Baby

There are a variety of ways to create an array.

Literal Constructor

Simply set a variable equal to []

arya = ["Stark", 7, "Thrones"] 
#=> ["Stark", 7, "Thrones"]

 

#new

Use the #new method on Array.

Array.new 
#=> []

You can give this method a number to give it a size.

Array.new(7) 
#=> [nil, nil, nil, nil, nil, nil, nil]

A bunch of nils are about as useful as a bunch of 💩, so let’s fill in that second available argument, which is the default object.

Array.new(7, "poop") 
#=> ["poop","poop","poop","poop","poop","poop","poop" ]

We can also pass it a block

Array.new(){"Arya"}
=> []

Well, we didn’t give it a size, what did you expect?

Array.new(3){"Arya"}
=> ["Arya", "Arya", "Arya"]

Let’s give it another object…

Array.new(3){Array.new}
=> [[], [], []]

The first array was told it was going to have a size of 3. In the block we say what we want three of: another silly array.

We could do better.

Array.new(3){["cheese"]}
=> [["cheese"], ["cheese"], ["cheese"]]

And now we have one of the major problems of life: not enough cheese.

Array.new(3){Array.new(3, "cheese")}
=> [["cheese", "cheese", "cheese"], ["cheese", "cheese", "cheese"], ["cheese", "cheese", "cheese"]]

That’s better. Cheese block fixed.

¯\_(ツ)_/¯

Array()

Finally, you can use Array(), which, under the hood, calls #to_ary followed by #to_a.

Array({:arya => "girl", :nymeria => "direwolf"})
=> [[:arya, "girl"], [:nymeria, "direwolf"]]

Array("needle")
=> ["needle"]

Array(3)
=> [3]

What’s going on with #to_ary and #to_a, you say?

#to_a does the converting of an object that is a child to Array, while #to_a simply returns that.

Although it has been deprecated apparently, so that was a long way of saying “don’t worry about it”.

See Ruby Docs for more joyous fun

One thought on “Let’s Make An [Array] Baby

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s