Popping, Pushing, Shifting

Since I like the word “pop” so much (see name). I figured I should read and write up on the pop method in addition to other 3 methods used in removing and moving elements from ruby arrays push, shift and unshift.

A different pop method

Push & Pop

(pushing and popping both happen at the end of an array.)

Push

The push method adds an element to the end of the array. We’ll walk through this using an example of an array of cheese as strings.

cheese = [ "Feta, "Gouda", "Brie"]
cheese.push("Havarti")

Now, if we run our code, the string “Havarti” will be added to the last elements spot.

cheese = [ "Feta, "Gouda", "Brie", "Havarti"]

Pop

The pop method is push’s counterpart. It is used to remove the last element from the array, or “pop” it out. I’m going to walk through the process using our same array of cheeses.

cheese = [ "Feta, "Gouda", "Brie"]
cheese.pop
cheese = ["Feta", "Gouda"]

After running pop, our array has dropped the Brie, however if we didn’t want to lose the “Brie” value, we can assign it to a variable.

a = cheese.pop
a= "Brie"
cheese = ["Feta", "Gouda"]

Unshift & Shift

(unshift & shift both happen at the start of an array.)

Unshift

The unshift method adds an element to the start of the array. We’ll walk through this using the same array as before.

cheese = [ "Feta, "Gouda", "Brie"]
cheese.unshift("Havarti")

Now, cheeses array returns as follows with Havarti in the first array slot.

cheese = ["Havarti" "Feta, "Gouda", "Brie"]

Shift

Similar as push and pop wore BFF necklaces so do unshift and shift. The shift method is used to remove the first element from the array. In this array we’re trying to now remove “Havarti” from the list.

cheese = ["Havarti" "Feta, "Gouda", "Brie"]
cheese.shift
cheese = [ "Feta, "Gouda", "Brie"]

TADA!

now you’re a poppin’, pushin’, shiftin’ pro.

Push It Real Good