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 の default と default_proc の違い

1
Posted at

Ruby の default と default_proc の違い

結論(最短)

  • default は「キーが無いときに返す値」

  • default_proc は「キーが無いときに実行される処理」

つまり

  • default → 値

  • default_proc → 動くコード(Proc)

役割がまったく違う。

1. default の動き(ただの値)

default は キーが存在しないときに返す “固定の値”。

h = Hash.new
h.default = 0

p h[:a]  # => 0
p h[:b]  # => 0

何回呼んでも 同じ値

例外は出ない

シンプルで安全

2. default_proc の動き(コードが実行される)

default_proc は キーが無いときに実行される Proc(関数)。

h = Hash.new { |hash, key| puts "#{key} は無いよ" }

h[:a]  # => "a は無いよ"

キーが無いときに毎回コードが動く

何でもできる(例外を投げる、値を生成する、ログを出す)

便利だけど危険性もある

3. default と default_proc の違い(表で理解)

項目 default default_proc
正体 値 Proc(コード)
動き そのまま返す 実行される
キーが無いとき 値を返す Proc が呼ばれる
例外 出ない 出すこともできる
使いどころ 安全・シンプル 高度な処理

4. 両方設定するとどうなる?

Ruby の仕様で

default を設定すると default_proc は無効になる
default_proc を設定すると default は無視される

つまり どちらか一方だけが有効。

5. 実例で違いを見る

default の場合

h = Hash.new
h.default = "なし"

p h[:x]  # => "なし"

default_proc の場合

h = Hash.new { |h, k| raise "Key #{k} missing" }

h[:x]  # => 例外発生

最終まとめ

  • default → 値を返すだけ(安全)

  • default_proc → コードが動く(強力)

  • 両方は同時に使えない

  • default_proc を nil にすると普通のハッシュに戻る

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