LoginSignup
0
0

More than 3 years have passed since last update.

RubyのHashのメモ

Last updated at Posted at 2020-08-01

リファレンス
rubyのhashがPythonの辞書と混ざって混乱してたときの自分用のメモです。
間違え等あったらコメントしてくださると幸いです。

環境

ruby 2.7.1

定義

下記すべてで定義できる

訂正コメント下さりありがとうございます。

irb
# 文字列 と =>
hash1={"first"=>"いち"}

# シンボル と =>
hash2={:first=>"いち"}

# キーがシンボルの場合の省略した書き方
# (:"first"→:first というシンボルができる)
hash3={"first":"いち"}

# キーがシンボルの場合の省略した書き方
hash4={first:"いち"}

当然これはできない

irb

#シンボル と :
hash5={:first:"いち"}
=>syntax error

中身は異なっている

  • hash1 → 文字列がキー
  • hash2,3,4 → シンボルがキー
irb
# hash1
{"first"=>"いち"}

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

呼び出すときは

irb
hash1["first"]
hash2[:first] #hash2,3,4共通

付録

気をつけないと間違えそう

Pythonのつもりで書くとやらかしそう...

irb

hoge="second"
hash5={hoge:2,hoge=>2}
#=> {:hoge=>2, "second"=>2}
0
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0