ruby Array.empty 的相反方法是什么?或 [].empty?红宝石

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11781658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:20:39  来源:igfitidea点击:

What is the opposite method of Array.empty? or [].empty? in ruby

ruby

提问by Kamilski81

I do realize that I can do

我确实意识到我可以做到

unless [1].empty? 

But I'm wondering if there is a method?

但我想知道是否有方法?

回答by noodl

As well as #any?as davidrac mentioned, with ActiveSupportthere's #present?which acts more like a truth test in other languages. For nil, false, '', {}, []and so on it returns false; for everything else true (including 0, interestingly).

除了#any?提到的davidrac 之外ActiveSupport还有#present?这更像是其他语言的真实测试。对于nilfalse''、 等{}[]它返回 false;对于其他一切都是真的(包括 0,有趣的是)。

回答by davidrac

You may use [1].any?, which is actually defined in Enumerable

您可以使用[1].any?,它实际上是在Enumerable 中定义的

Note that this will not work in case your array hold only nil or false values (thanks for the comment @InternetSeriousBusiness).

请注意,如果您的数组仅包含 nil 或 false 值,这将不起作用(感谢@InternetSeriousBusiness 的评论)。

回答by Rod McLaughlin

[nil].any?
=> false
[nil].any? {|something| true}
=> true
[].any? {|something| true}
=> false
[false, false].any? {|something| true}
=> true
[nil, 'g'].any? {|something| true}
=> true

回答by CRandER

No single method I know of is going to give you that in Ruby. Key word 'single':

我所知道的任何一种方法都不会在 Ruby 中为您提供这种方法。关键词“单身”:

[5].size.positive? => true
[5].size.nonzero? => 1

[].size.positive? => false
[].size.nonzero? => nil

Both of these are even more useful with the safe navigation operator, since nil returns falsy, meaning negative methods (like #empty?) break down a bit:

这两个对于安全导航操作符更有用,因为 nil 返回假,意味着否定方法(如#empty?)有点分解:

# nil considered 'not empty' isn't usually what you want
not_empty = proc{|obj| !obj&.empty? }

not_empty.call nil => true
not_empty.call [ ] => false
not_empty.call [5] => true


# gives different 3 answers for the 3 cases
# gives truthy/falsy values you'd probably expect
positive_size = proc{|obj| obj&.size&.positive? }

positive_size.call nil => nil
positive_size.call [ ] => false
positive_size.call [5] => true


# gives truthy/falsy values you'd probably expect
nonzero_size = proc{|obj| obj&.size&.nonzero? }

nonzero_size.call nil => nil
nonzero_size.call [ ] => nil
nonzero_size.call [5] => 1

回答by vidur punj

To check for elements in array :
.empty?
.present?

检查数组中的元素:
.empty?
。展示?

if a={}
a.any? .nil?
will gives you false.

如果 a={}
a.any? 。零?
会给你假的。

To check whether or not a field has a non-nil value:

要检查字段是否具有非 nil 值:

.present?
.nil?
.any?