を返したいmycollection.first.user.nameのですが、mycollectionまたはmycollection.firstnilかもしれません。次のコードは醜いですが、動作します:
if mycollection && mycollection.first && mycollection.first.user
mycollection.first.user.name
end
ルビー流とは?
を返したいmycollection.first.user.nameのですが、mycollectionまたはmycollection.firstnilかもしれません。次のコードは醜いですが、動作します:
if mycollection && mycollection.first && mycollection.first.user
mycollection.first.user.name
end
ルビー流とは?
If you happen to be using Rails, it adds a method to Object called try which might help:
mycollection.try(:first).try(:user).try(:name)
That will call first, user, and name in sequence, but if any of the values in the chain is nil, it will just return nil without throwing an exception.
If you're not using Rails, you can define it yourself very easily:
class Object; def try(method,*args,&block); send(method,*args,&block); end end
class NilClass; def try(method,*args,&block); nil; end end
一部の人々は、try() にあまり熱心ではありませんが、確かに、あなたが好むかもしれない 1 つのアプローチです。
name = mycollection.try(:first).try(:user).try(:name)
name は、何かが nil の場合は nil になるか、name の値を返します。
さらに、次のように呼び出すことができるように、モデルをリファクタリングすることもできます。
item.user_name
class ItemClass
def user_name
user.try(:name)
end
end
アイテムはコレクションの最初のものです。
name = if mycollection && item = mycollection.first
item.user_name
end
純粋な Ruby では、次のことができます。
if mycollection && mycollection.first.respond_to?(:user)
mycollection.first.user.name
end
これmycollectionは、空の配列の場合、mycollection.firstnil が返されるためです。
irb(main):002:0> nil.respond_to?(:user)
false