LoginSignup
2
3

More than 5 years have passed since last update.

nilの可能性があるオブジェクトに便利なtryメソッド

Last updated at Posted at 2015-11-13

オブジェクトがnilの時NoMethodErrorが返ってくるので、nilチェックが必要になる。その対応にActiveSupportのtryを使うと便利です。

hoge_name = hoge ? hoge.name : 'hoge'
# try使うと
hoge_name = hoge.try(:name) || 'hoge'


@hoge = Hoge.all
hoge_id = @hoge.id if @hoge
# try使うと
hoge_id = @hoge.try(:id)


# view(slim)の場合
div
 = "名前: #{@hoge.name unless @hoge.nil?}"
# try使うと
div
 = "名前: #{@user.try(:name)}"

引数も使えるみたいです。

参考
http://apidock.com/rails/Object/try

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