0
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?

More than 3 years have passed since last update.

# Rubyでハッシュの引数にデフォルト値を渡せるという基本をまるで知らなかった。もうキーワード引数のエラーに怯えない。

0
Last updated at Posted at 2019-11-16

Ruby keyword arguments raises "unknown keyword (ArgumentError) " so use hash keyword with default value

Hash argument

class Alice
  def initialize(options = { nickname: :liddel })
    @options = options
  end

  def nickname
    @options[:nickname]
  end
end

p Alice.new.nickname
# :liddel

# unknown hash value ignored, not raise error
p Alice.new(nickname: :wonder, sex: :woman).nickname
# :wonder

Keyword argument

class Bob
  def initialize(nickname: :phantom)
    @nickname = nickname
  end

  def nickname
    @nickname
  end
end

p Bob.new.nickname
# :phantom

p Bob.new(nickname: :animal, sex: :man).nickname
# `initialize': unknown keyword: sex (ArgumentError)

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

0
0
0

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
0
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?