LoginSignup
0
0

More than 5 years have passed since last update.

Rubyのハッシュの小さなサンプルメモ

Last updated at Posted at 2018-12-01

概要

Rubyのハッシュの型と書き方に関するメモ
ほぼ「参考」先のURLのまま

メモ

確認用のメソッド

require "pp"

# 引数のハッシュの型を出力
def print_hash_types(hash)
  pp hash
  hash.each do |key, value|
    print key.class
    print ", "
    p value.class
  end
end

基本の記法と型について

ハッシュは任意の種類のオブ ジェクト(キー)から任意の種類のオブジェクト(値)への関連づけを行うことができます。
https://docs.ruby-lang.org/ja/latest/class/Hash.html

とのことで、以下のようにカオスな感じでもハッシュとして格納OK

hash1 = {
  0 => 2,
  1 => "a",
  "a" => 0,
  [0,1,2] => "f",
  true => 123,
  0.12 => false,
  false => :b
}
print_hash_types(hash1)

実行結果

{0=>2, 1=>"a", "a"=>0, [0, 1, 2]=>"f", true=>123, 0.12=>false, false=>:b}
Integer, Integer
Integer, String
String, Integer
Array, String
TrueClass, Integer
Float, FalseClass
FalseClass, Symbol

キーがシンボルの場合(1)

以下のように記載可能

hash2 = { a: "A", b: "B" }
print_hash_types(hash2)

実行結果

{:a=>"A", :b=>"B"}
Symbol, String
Symbol, String

キーがシンボルの場合(2)

hash3 = { "a": "A", "b": "B" }
print_hash_types(hash3)

実行結果

{:a=>"A", :b=>"B"}
Symbol, String
Symbol, String

参考

class Hash (Ruby 2.5.0) https://docs.ruby-lang.org/ja/latest/class/Hash.html

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