LoginSignup
2
1

More than 5 years have passed since last update.

ruby on rails hashの判定文

Last updated at Posted at 2017-07-18

1.エラーその1

hoge.ruby
hoge.merge!(hash[i]) if hash.present?

→この方法だとhash[i]がnilっている時にエラーになる。

no implicit conversion of nil into

2.エラーその2

hoge.ruby
hoge.merge!(hash[i]) if hash[i].present?

→この記述だと一見いけそうだが、やはりエラーになる

undefined method `[]' for nil:NilClass

3.良い書き方

hoge.ruby
hoge.merge!(hash[i]) if hash.try(:[],i).present?

→これでtryをかけるのでhash[i]が無い時は実行されずエラーにならない

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