これは何?
SSIA
確認環境
$ bundle exec ruby --version
ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-darwin19]
動作確認
キーワード引数
$ irb
irb(main):001:1* def hoge(a:, b:)
irb(main):002:1* p "a: #{a}"
irb(main):003:1* p "b: #{b}"
irb(main):004:0> end
=> :hoge
irb(main):005:0> hoge(3, 4)
Traceback (most recent call last):
5: from /Users/xxxx/.rbenv/versions/2.7.5/bin/irb:23:in `<main>'
4: from /Users/xxxx/.rbenv/versions/2.7.5/bin/irb:23:in `load'
3: from /Users/xxxx/.rbenv/versions/2.7.5/lib/ruby/gems/2.7.0/gems/irb-1.2.6/exe/irb:11:in `<top (required)>'
2: from (irb):5
1: from (irb):1:in `hoge'
ArgumentError (wrong number of arguments (given 2, expected 0; required keywords: a, b))
irb(main):006:0> hoge(a: 3, b: 4)
"a: 3"
"b: 4"
=> "b: 4"
余分なキーワードがある場合、エラーになります。
irb(main):013:0> hoge(a: 1, b: 2, c: 4)
Traceback (most recent call last):
6: from /Users/xxxx/.rbenv/versions/2.7.5/bin/irb:23:in `<main>'
5: from /Users/xxxx/.rbenv/versions/2.7.5/bin/irb:23:in `load'
4: from /Users/xxxx/.rbenv/versions/2.7.5/lib/ruby/gems/2.7.0/gems/irb-1.2.6/exe/irb:11:in `<top (required)>'
3: from (irb):12
2: from (irb):13:in `rescue in irb_binding'
1: from (irb):1:in `hoge'
ArgumentError (unknown keyword: :c)
ハッシュを渡す場合、**
を引数につけないと警告が出るようですが、私の環境では出ませんでした。
irb(main):010:0> b2 = {a: 6, b: 7}
=> {:a=>6, :b=>7}
irb(main):011:0> hoge(b2)
"a: 6"
"b: 7"
=> "b: 7"
irb(main):014:0> hoge(**b2)
"a: 6"
"b: 7"
=> "b: 7"
オプション引数
irb(main):015:1* def fuga(a:, **opts)
irb(main):016:1* p "a: #{a}"
irb(main):017:1* p "opts: #{opts}"
irb(main):018:0> end
=> :fuga
irb(main):019:0> fuga(a: 3, b: 3)
"a: 3"
"opts: {:b=>3}"
=> "opts: {:b=>3}"
irb(main):020:0> fuga(a: 3)
"a: 3"
"opts: {}"
=> "opts: {}"
irb(main):021:0> fuga({a: 3})
"a: 3"
"opts: {}"
=> "opts: {}"