LoginSignup
0
0

More than 3 years have passed since last update.

Ruby ハッシュの値の取得方法

Posted at

ハッシュには3種類の定義方法があります。
①キーに文字列を使う方法
 hash1 = { "sample" => "例" }
②キーにシンボルを使う方法
 hash2 = { :sample => "例" }
③キーにシンボルを使う方法(②よりもシンプル)
 hash3 = { sample: "例" } 

①を使用した場合のハッシュの値の取得の仕方は、ハッシュ["取得したい値のキー"]です。

例)

qiita.rb
favorites = { "fruit" => "いちご", "subject" => "数学" }
puts favorites["fruit"]

②と③を使用した場合のハッシュの値の取得の仕方は、ハッシュ[:取得したい値のキー]です。

例)

qiita.rb
favorites = { :fruit => "いちご", :subject => "数学" }
puts favorites[:subject]
favorites = { fruit:  "いちご", subject: "数学" }
puts favorites[:subject]

ハッシュの定義方法によって、値の取得の仕方が異なります。

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