Array Growth

There are a variety of ways to add items to an array.

In the beginning…

There was #unshift. If you want to add something in the beginning, use it.

how_much = ["many", "slams", "in", "an", "old", "screen", "door"]

how_much.unshift("how")
=> ["how", "many", "slams", "in", "an", "old", "screen", "door"]

In the end…

You can always use #push, which could handle just one or multiple arguments. There’s also fun to be had in chaining it.

how_much =["how", "many", "slams", "in", "an", "old", "screen", "door"]

how_much.push("depends")
=> ["how", "many", "slams", "in", "an", "old", "screen", "door", "depends"]

how_much.push("how", "loud")
=> ["how", "many", "slams", "in", "an", "old", "screen", "door", "depends", "how", "loud"]

how_much.push("you").push("shut").push("it")
=> ["how", "many", "slams", "in", "an", "old", "screen", "door", "depends", "how", "loud", "you", "shut", "it"]

The same fun can be had with #<<

how_much = ["how", "many", "slices", "in", "a", "bread"]

how_much << "depends"
=> ["how", "many", "slices", "in", "a", "bread", "depends"]

how_much << ["how", "thin"]
=> ["how", "many", "slices", "in", "a", "bread", "depends", ["how", "thin"]]

how_much << "you" << "cut" << "it"
=> ["how", "many", "slices", "in", "a", "bread", "depends", ["how", "loud"], "you", "cut", "it"]

Everywhere else

With #insert, we can give an index to indicate where we’d like things to go before giving the object(s) that will be going there. Notice that it pushes things around to accommodate¬†our request that this new object goes where we want and everything else needs to fall in line.

how_many = ["how", "much", "inside", "a", "day"]

how_many.insert(2, "good")
=> ["how", "much", "good", "inside", "a", "day"]

how_many.insert(-1, "depends", "how", "good", "you", "live")
=> ["how", "much", "good", "inside", "a", "day", "depends", "how", "good", "you", "live"]

 

“How Many, “How Much” -Shel Silverstein

How many slams in an old screen door?
Depends how loud you shut it.
How many slices in a bread?
Depends how thin you cut it.
How much good inside a day?
Depends how good you live ’em.
How much love inside a friend?
Depends how much you give ’em.

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s