これを宣言する良い方法はありますか?私がやろうとしている何配列にルビの項目があるかどうかを調べる
if current_user.received_replies.unread.count > 0
は、少なくとも一つのunread
オブジェクトがあります場合にのみ、一致条件です。
これを宣言する良い方法はありますか?私がやろうとしている何配列にルビの項目があるかどうかを調べる
if current_user.received_replies.unread.count > 0
は、少なくとも一つのunread
オブジェクトがあります場合にのみ、一致条件です。
unless current_user.received_replies.unread.empty?
# ...
end
それとも、あなたのif
はelse
を持っている場合(unless/else
は地獄のように非常に醜いですので)、ケースを切り替える:
if current_user.received_replies.unread.empty?
# ...
else
# ...
end
これは少し良いかもしれ:
unless current_user.received_replies.unread.empty?
私は使用するだろう:
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
リストに偽のアイテムが含まれていると、これは完全には一致しません。 'ActiveRecord'のドメインでは実行可能かもしれませんが、一般的には真実ではない'空の? 'の否定だと思ったところで、これについて多くの混乱が見られました。 –
@ NiklasB。うわー、私はそれに気付かなかった。 '[false] .any?'は 'false'という厄介な種類です。 –
@Andrew:それはなぜでしょうか?通常、この関数は '[1,2,3] .any?のような項目の* any *が述語に保持されているかどうかをチェックします。 {| x | x> 2} 'となる。ブロックなしでも機能するのは残念なことです(どこに役立つか分かりません)。 @ NiklasB。 –