LoginSignup
13
8

More than 5 years have passed since last update.

Hashだったらキーの値、nilだったらnilがほしいとき

Posted at

Hashインスタンスかnilか分からない変数があって、Hashインスタンスだったらキーに紐づく値がほしい、nilだったらnilのままでいい、そんなコードが書きたくなることがある。

単純に書くと下記のようになるが、変数名を2度書くのが面倒だ。

a = {foo: 1}
b = a ? a[:foo] : nil
b = a && a[:foo]

Ruby 2.3.0以降なら「ぼっち演算子(safe navigation operator)」が使える。

b = a&.[](:foo)

NilClass#to_h で {} が返るので、下記のようにする手もある。

b = a.to_h[:foo]
13
8
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
13
8