Help us understand the problem. What is going on with this article?

Object#try

More than 5 years have passed since last update.

有名だけど。。。

relation

Book belongs to Author
Author has_many Books

model

author = Author.create!(name: 'foo')
book1 = Book.create!(title: 'bar')
book2 = Book.create!(title: 'baz', author_id: author.id)

課題: よくあるエラー

book1.author.name
# => NoMethodError: undefined method `name' for nil:NilClass

解決策 3項演算子

book1.author.present? ? book1.author.name : 'unknown'
# => "unknown"
book2.author.present? ? book2.author.name : 'unknown'
# => "foo"

解決策 Object#try

book1.author.try(:name) || 'unknown'
# => "unknown"
book2.author.try(:name) || 'unknown'
# => "foo"

Object#tryの使い方

メソッドの引数を渡す

x = [1, 2, 3]
x.try(:delete, 1)
# => 1
pp x
# => [2, 3]

メソッドのブロックを渡す

x = nil
x.try(:map){|o| o.to_i }
# => nil
y = %w(1 2 3 4 5)
# => ["1", "2", "3", "4", "5"]
y.try(:map){|o| o.to_i }
# => [1, 2, 3, 4, 5]

※別解

y.try(:map, &:to_i)

tryにブロックを渡す

x = nil
x.try {|o| o.sum / o.size } || 0
# => 0
y = [1, 2, 3, 4, 5]
y.try {|o| o.sum / o.size } || 0
# => 3

see:
https://github.com/rails/rails/blob/6ef9fda1a39f45e2d18aba4881f60a19589a2c77/activesupport/lib/active_support/core_ext/object/try.rb#L32
https://github.com/rails/rails/blob/6ef9fda1a39f45e2d18aba4881f60a19589a2c77/activesupport/lib/active_support/core_ext/object/try.rb#L54

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away