我意识到我可以做到
unless [1].empty?
但我想知道是否有方法?
答案 0 :(得分:83)
与davidrac提到的#any?
一样,ActiveSupport #present?的行为更像是其他语言的真值测试。对于nil
,false
,''
,{}
,[]
等,它会返回false;其他一切都是真的(包括0,有趣的是)。
答案 1 :(得分:19)
您可以使用[{1}}
中实际定义的[1].any?
请注意,如果您的数组只保留nil或false值,这将不起作用(感谢评论@InternetSeriousBusiness)。
答案 2 :(得分:9)
[nil].any?
=> false
[nil].any? {|something| true}
=> true
[].any? {|something| true}
=> false
[false, false].any? {|something| true}
=> true
[nil, 'g'].any? {|something| true}
=> true
答案 3 :(得分:1)
在Ruby中,我所知没有一种方法可以为您提供这种方法。关键字“单”:
[5].size.positive? => true
[5].size.nonzero? => 1
[].size.positive? => false
[].size.nonzero? => nil
这两种方法对于安全的导航操作员来说都更加有用,因为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
答案 4 :(得分:0)
检查数组中的元素:
.empty?
.present?
如果a = {}
a.any? .nil?
会给你假的。
检查字段是否具有非零值:
.present?
.nil?
.any?