light log

学んだこととか

RubyのHashについて基本的な記法を調べた

Railsの本を読んでいて、Hashの記法がよくわかってない気がしたのでちょっと調べた。

キーワード引数についても少し。

# 普通の記法
hash = {"foo" => 1, "bar" => 2}

# キーがシンボルの場合、
# これが
hash_symbols1 = {:foo => 1, :bar => 2}
# こう書ける
hash_symbols2 = {foo: 1, bar: 2}

p hash_symbols1 == hash_symbols2
# => true

#-------------------------------------------
def show_hash(hash)
  hash.each do |k, v|
    puts "#{k} => #{v}"
  end
end

# 引数の最後がハッシュの場合、{}は省略可能
show_hash "foo" => 1, "bar" => 2, "baz" => 3

# むしろここで{}を省略しないとsyntax errorになる(ブロックとして解釈される?)
# show_hash {"foo" => 1, "bar" => 2, "baz" => 3} # これはエラーになる

# ()で囲むとOK
show_hash({"foo" => 1, "bar" => 2, "baz" => 3})

# キーがシンボルの場合、どっちもOK
show_hash :foo => 1, :bar => 2, :baz => 3
show_hash foo: 1, bar: 2, baz: 3

#-------------------------------------------
# キーワード引数
def show_arguments(foo: 0, bar: 0, baz: 0)
  p foo: foo, bar: bar, baz: baz
end

# 呼び出し方はシンボルのハッシュのときと同じ
show_arguments foo: 1, bar: 2, baz: 3