1. kengos@github

    Posted

    kengos@github
Changes in title
+Object#try
Changes in tags
Changes in body
Source | HTML | Preview
@@ -0,0 +1,86 @@
+有名だけど。。。
+
+### 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)
+```
+
+## 課題: よくあるエラー
+
+```ruby
+book1.author.name
+# => NoMethodError: undefined method `name' for nil:NilClass
+```
+
+### 解決策 3項演算子
+
+```ruby
+book1.author.present? ? book1.author.name : 'unknown'
+# => "unknown"
+book2.author.present? ? book2.author.name : 'unknown'
+# => "foo"
+```
+
+### 解決策 Object#try
+
+```ruby
+book1.author.try(:name) || 'unknown'
+# => "unknown"
+book2.author.try(:name) || 'unknown'
+# => "foo"
+```
+
+## Object#tryの使い方
+
+### メソッドの引数を渡す
+
+```ruby
+x = [1, 2, 3]
+x.try(:delete, 1)
+# => 1
+pp x
+# => [2, 3]
+```
+
+### メソッドのブロックを渡す
+
+```ruby
+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]
+```
+
+※別解
+
+```ruby
+y.try(:map, &:to_i)
+```
+
+### tryにブロックを渡す
+
+```ruby
+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