Ruby入門 PART9 (キーワード付き引数(Ruby 2.0以降)) (全11回)

パーフェクトRubyを読んで、重要なポイント等をメモしていきます.
キーワード付き引数
1 2 3 4 5 6 7 8 9 10 11 12 |
def test(a: 0, b:nil) p a p b end test(a: 1, b: "aa") # キーワードを指定しないとエラー begin test(1, "aa") # Error! wrong number of arguments rescue end |
順序が変わっても問題なく受け取れる
1 2 3 4 5 6 7 |
def test2(a:0, b:nil, **option) p a # => 1 p b # => "bb" p option # {:c=>"aaa", :d=>"wao"} end test2(b:"bb", a:1, c:"aaa", d:"wao") |
キーワード付き引数+オプション引数ハッシュ
1 2 3 4 5 6 7 |
def test2(a: 0, b:nil, **option) p a p b p option # {:c=>"aaa", :d=>"wao"} end test2(a:10, b:"bb", c:"aaa", d:"wao") |
通常引数+オプション引数ハッシュ
1 2 3 4 5 6 7 |
def test2(a, b, **option) p a p b p option # {:c=>"aaa", :d=>"wao"} end test2(10, "bb", c:"aaa", d:"wao") |
関連記事一覧
- タグ:
- Ruby