1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

メソッドの最後の引数がハッシュなら {} は省略できる(Ruby)

Posted at

実例

例えば、次のようなコードを考えてみる。

def greet(name, options = {})
  greeting = "私の名前は#{name}です。"
  greeting += "年齢は#{options[:age]}です。" if options[:age]
  greeting += "好きな食べ物は#{options[:food]}です。" if options[:food]
  greeting
end

もしこのようなメソッドが存在した場合、メソッドを呼び出す時には

greet("鈴木", { age: 25, food: "りんご" })

# => 私の名前は鈴木です。年齢は25です。好きな食べ物はりんごです。

ではなく

greet("鈴木", age: 25, food: "りんご" )

と書くことができる。この仕様を知らないと混乱することもあると思うので書き残しておく。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?