Posted at

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