[Ruby] [Understanding] Difference between hash and array in Ruby

less than 1 minute read


I was learning ruby and could only understand the hashes and arrays that I often see, but since I finally understood it, I summarized it! You can see the difference between hash and array by looking at this! (Perhaps)

First, the array

An array is like this

name = ["Suzuki","Tanaka" ,"Onishi"]
  • Multiple elements lined up
  • Surrounded by []
  • Elements are separated by ,
  • Subscripts are specified as integers in order from the beginning (in the above case, name(1) => "Tanaka")

What is a hash?

Hash is like this

name = {a: "Suzuki", b: "Tanaka" ,c: "Onishi"}
  • Hash is essentially the same as array
  • Surrounded by {}
  • ** You can specify a key (subscript) other than an integer! **This may be all (name[:a] => "Suzuki" in the above case)

Why use {} when they are essentially the same

If the hash is surrounded by [], it’s easy to lose track of where the attribute is and what the key is, so what’s surrounded by {} is the hash! It seems that it is used to make it easy to understand!

Knowing this will make it easier to tell when studying or reading code!

that’s all~