[RAILS] Ruby arrays, hashes, and symbols are confusing, so I summarized them.

Introduction

I'm doing a Rails tutorial, what is "hash"? How many times did I get it, so I thought I'd put it together properly.

Array

The first element of the array (“A” in the following case) is 0.

    hiragana = ["Ah", "I ", "U "]
    puts a[0] #Show that
    puts a[1] #Show
    puts a[2] #Show

hash

Unlike arrays, hashes can handle elements using keys that they define, such as "first".

    a = { "first" => 1, "second" => 2 }
    puts a["first"] #Display as 1
    puts a["second"] #Display as 2

Hashes and symbols

Symbols are like strings. It seems that it is often combined with hashes.

    hush1 = { :first => 1, :second => 2 }
    puts hush1[:first] #Display as 1
    puts hush1[:second] #Display as 2
    hush2 = { first: 1, second: 2}
    puts hush2[:first] #Display as 1
    puts hush2[:second] #Display as 2

    hush1 == hush2 #Become true

Personally, I prefer the writing style of hush2. Because the description is the same as Javascript.

【reference】 https://qiita.com/iron-breaker/items/32710004f0bb2e2babb6

Recommended Posts

Ruby arrays, hashes, and symbols are confusing, so I summarized them.
About Ruby hashes and symbols
Summary of hashes and symbols in Ruby
[Understanding] Differences between hashes and arrays in Ruby
Symbols and Destructive Ruby
I passed Ruby Gold, so I summarized the study methods (November 2020 version)