Why use Arrays or Hashes?

By on

Arrays and hashes are pretty similar, accessing them is different. So when stuff is deleted in a hash, the key and the value are gone while in an array, the object is the only thing deleted.

my_array = ["guitar", "trumpet", "xylophone"]

In this example, guitar is accessed by it’s position or index in the array which is my_array[0].

When using hashes, you can access a value using a key. So here, guitar is accessed by it’s key, my_hash["string"].

my_hash = { "string" => "guitar", "brass" => "trumpet", "percussion" => "xylophone" }

So when I delete guitar in my_array, my_array[0] is now trumpet.

my_array = ["trumpet", "xylophone"]

But when I delete guitar in my_hash, my_hash["string"] is nil.

my_hash = { "brass" => "trumpet", "percussion" => "xylophone" }

Feedback