LoginSignup
12
16

More than 5 years have passed since last update.

nilの可能性がある、ネストしたHASHの値を1行で取得する方法

Last updated at Posted at 2015-06-08

解決したいこと

if文を使わずに、params[:foo][:bar]のとき、barがnilでなければ、`params[:foo][:bar]の値を返したい
また、nilの場合は、nilを返したい。

よくあるエラー

> params[:foo][:bar]
NoMethodError: undefined method `[]' for nil:NilClass

解決策

ActiveSupportのtryを使う。HASHの場合は、:[]が大事

params[:foo].try(:[], :bar)

参考

http://guides.rubyonrails.org/active_support_core_extensions.html
http://stackoverflow.com/questions/6224875/equivalent-of-try-for-a-hash
Writing Ruby Square Bracket Methods

12
16
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
12
16