2012-04-26 5 views

答えて

4
unless current_user.received_replies.unread.empty? 
    # ... 
end 

それとも、あなたのifelseを持っている場合(unless/elseは地獄のように非常に醜いですので)、ケースを切り替える:

if current_user.received_replies.unread.empty? 
    # ... 
else 
    # ... 
end 
1

これは少し良いかもしれ:

unless current_user.received_replies.unread.empty? 
2

私は使用するだろう:

if current_user.received_replies.unread.any? 

ドキュメントから:

 
= Array.any? 

(from ruby core) 
=== Implementation from Enumerable 
------------------------------------------------------------------------------ 
    enum.any? [{|obj| block } ] -> true or false 

------------------------------------------------------------------------------ 

Passes each element of the collection to the given block. The method returns 
true if the block ever returns a value other than false or nil. If the block 
is not given, Ruby adds an implicit block of {|obj| obj} (that is any? will 
return true if at least one of the collection members is not false or nil. 

     %w{ant bear cat}.any? {|word| word.length >= 3} #=> true 
     %w{ant bear cat}.any? {|word| word.length >= 4} #=> true 
     [ nil, true, 99 ].any?       #=> true 
+1

リストに偽のアイテムが含まれていると、これは完全には一致しません。 'ActiveRecord'のドメインでは実行可能かもしれませんが、一般的には真実ではない'空の? 'の否定だと思ったところで、これについて多くの混乱が見られました。 –

+0

@ NiklasB。うわー、私はそれに気付かなかった。 '[false] .any?'は 'false'という厄介な種類です。 –

+0

@Andrew:それはなぜでしょうか?通常、この関数は '[1,2,3] .any?のような項目の* any *が述語に保持されているかどうかをチェックします。 {| x | x> 2} 'となる。ブロックなしでも機能するのは残念なことです(どこに役立つか分かりません)。 @ NiklasB。 –

関連する問題