Ruby on rails 评估数组在ruby中是否有任何项
有没有更好的方式来申报Ruby on rails 评估数组在ruby中是否有任何项,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,有没有更好的方式来申报 if current_user.received_replies.unread.count > 0 我试图做的是,仅当至少有一个未读对象时才匹配条件 unless current_user.received_replies.unread.empty? # ... end 或者,如果您的if有一个else,则切换案例(因为除非/else非常糟糕): 这可能会好一点: unless current_user.received_replies.unread.emp
if current_user.received_replies.unread.count > 0
我试图做的是,仅当至少有一个未读对象时才匹配条件
unless current_user.received_replies.unread.empty?
# ...
end
或者,如果您的if
有一个else
,则切换案例(因为除非/else
非常糟糕):
这可能会好一点:
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
=Array.any?
(来自ruby core)
==可枚举的实现
------------------------------------------------------------------------------
有吗?[{obj | block}]->对还是错
------------------------------------------------------------------------------
将集合的每个元素传递给给定的块。该方法返回
如果块返回的值不是false或nil,则为true。如果街区
如果没有给定,Ruby会添加一个{| obj | obj}的隐式块(即任意?will)
如果至少有一个集合成员不是false或nil,则返回true。
%w{ant bear cat}。有任何?{word | word.length>=3}{35;=>正确吗
%w{ant bear cat}。有任何?{word | word.length>=4}{35;=>正确吗
[零,对,99]。有吗?#=>对
如果列表中包含虚假的项目,那就不太一样了。在ActiveRecord
域中,这可能是可行的,但我看到了很多关于这一点的困惑,人们认为这只是对empty?
的否定,这在一般情况下是不正确的。@NiklasB.Wow我从来没有注意到这一点。有点讨厌[false].any?
是false
@Andrew:为什么不呢?通常这个函数是检查谓词是否适用于任何项,如[1,2,3]。any?{x | x>2}
。不幸的是,它也可以在没有块的情况下工作(我不知道它在哪里有用).@NiklasB.这就是我的观点,没有块的版本是误导性的,并且似乎不会立即传达其真实性检查。我同意它不应该存在。我发现非块版本非常有用,但我知道我的数组将包含真实元素。如果你不知道数组中有什么,块非常适合提供深层元素元素的er检查。如果我有一个未知元素类型的数组,我想我的问题比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