Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

概要

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

https://docs.ruby-lang.org/ja/latest/doc/spec=2fliteral.html#hash

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away