有没有更好的方法来声明这个?
if current_user.received_replies.unread.count > 0
我想要做的只是在至少有一个unread
对象的情况下匹配条件。
答案 0 :(得分:4)
unless current_user.received_replies.unread.empty?
# ...
end
或者,如果您的if
有一个else
,请切换案例(因为unless/else
很难得):
if current_user.received_replies.unread.empty?
# ...
else
# ...
end
答案 1 :(得分:3)
我会用:
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
答案 2 :(得分:1)
这可能会更好一点:
unless current_user.received_replies.unread.empty?