0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Ruby ハッシュとシンボルの記法 まとめ

Posted at

Railsチュートリアル
ハッシュとシンボルの書き方

user = {} # {}は空のハッシュ
=> {}
user["first_name"] = "hurihata" # キーが "first_name" で値が "hurihata"
=> "hurihata"
user["last_name"] = "koyo" # キーが "last_name" で値が "koyo"
=> "koyo"
user["first_name"] # 要素へのアクセスは配列の場合と似ている
=> "hurihata"
user # ハッシュのリテラル表記
=> {"last_name"=>"koyo", "first_name"=>"hurihata"}

ハッシュのキーとしてシンボルを採用する場合、user のハッシュは次のように定義できる

一つめの記法

user = { :name => "koyo", :email => "kkkk@XXX.com" }
=> {:name=>"koyo", :email=>"kkkk@XXX.com"}
user[:name] # :name に対応する値にアクセスする
=> "koyo"
user[:password] # 未定義のキーに対応する値にアクセスする
=> nil

二つめの記法

{ name: "koyo", email: "kkkk@XXX.com" }

自分的にはハッシュロケット(=>)を使う一つ目の記法より二つ目のシンボルの:を後ろにつける記法の方が見やすく使いやすいと感じた。

0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?