Ruby Hash notes

Reference This is a memo for myself when I didn't understand the hash of ruby. If you make a mistake, please comment.

environment

ruby 2.7.1

Definition

Can be defined by all of the following

Thank you for your correction comment. "


#String and=>
hash1={"first"=>"Ichi"}

#With symbols=>
hash2={:first=>"Ichi"}

#Omitted writing when the key is a symbol
#(:"first"→:You can create the symbol first)
hash3={"first":"Ichi"}

Omitted writing when the key is a symbol
hash4={first:"Ichi"}

Of course this is not possible

#With symbols:
hash5={:first:"Ichi"}
=>syntax error

The contents are different

--hash1 → String is the key --hash2,3,4 → Symbol is the key

#hash1
{"first"=>"Ichi"}

#hash2,3,4
 {:first=>"Ichi"}

When calling


hash1["first"]
hash2[:first] #hash2,3,4 common

appendix

If you're not careful, you might make a mistake


hoge="second"
hash5={hoge:2,hoge=>2}
hash5
=> {:hoge=>2, "second"=>2}

You can also do this


hash={"first"=>1,:first=>"Ichi"}

Recommended Posts

Ruby Hash notes
[Ruby] Hash retrieval
[ruby] Double hash
Ruby double hash
Ruby Thread # [] = method notes
Ruby study notes (puts)
Hash
[Ruby] Notes on gets method
Ruby study notes (variables & functions)
About the behavior of ruby Hash # ==
Extraction of "ruby" double hash * Review
[Ruby] Extracting double hash in array
[Ruby] Array
Ruby basics
Ruby learning 5
[Ruby] Writing notes for cherry books [Notes for yourself]
Ruby basics
JUnit 4 notes
Ruby Review 2
Ruby addition
Ruby learning 3
java notes
Notes on using FCM with Ruby on Rails
Ruby setting 2
Ruby problem ⑦
Ruby learning 2
[Ruby] Block
Refactoring Ruby
ruby calculator
Ruby learning 6
synchronized notes
Ruby settings 1
Hash basics
Refactoring Ruby
Ruby basics
Ruby memo
Ruby learning 1
Ruby Review 1
[Ruby] Module
AtCoder ABC127 D hash to solve with Ruby 2.7.1
[For Ruby beginners] Ruby engineer certification exam Silver/Gold exam notes