🐥

関数のキーワード引数をハッシュで受け取る方法

2023/08/12に公開

概要

Rubyにおける、関数のキーワード引数をハッシュで受け取る方法を記載します。

やってみる

def method1(**hash)
  pp hash # {:id=>1, :title=>"ホワイトラビット", :author=>"伊坂 幸太郎"}

  pp hash[:id] # 1
  pp hash[:title] # "ホワイトラビット"
  pp hash[:author] # "伊坂 幸太郎"
end

method1(id: 1, title: 'ホワイトラビット', author: '伊坂 幸太郎')

以上です。

環境

  • ruby 3.2.2 (2023-03-30 revision e51014f9c0) [x86_64-linux]

Discussion