0
0

デフォルト値付きのHashを宣言する

Posted at

やりたかったこと

{ x:1, y:2 } みたいなハッシュを宣言しつつデフォルト値も与えるっていうのを1行でやりたかった。

パターン1 : Hash.new + merge

ハッシュを定義しつつデフォルト値も、っていう魔法のメソッドは無くて、2つのメソッドをチェーンするしかないっぽい。
悪くはないけど Hash.new ってあんまり馴染みが無いから若干意図が伝わりづらい気もする。

hash = Hash.new(5).merge(x: 1, y: 2)

hash[:x] #=> 1
hash[:y] #=> 2
hash[:z] #=> 5

パターン2 : ハッシュリテラル + tap

さっきより長くなっちゃったけど、こっちの方が意図が明確で好きかな。

hash = { x: 1, y: 2 }.tap { |h| h.default = 5 }

hash[:x] #=> 1
hash[:y] #=> 2
hash[:z] #=> 5
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