开发者

What's the shortest way to see if all the elements are not nil?

Is there a开发者_Go百科 more direct way to do this?

[1, nil, 2, 'a'].all? {|x| x}


Use include? and add a "not" to the beginning:

![1, nil, 2, 'a'].include?(nil)

If all elements are non-nil then the array does not include nil. Using .all? means that you have to scan the entire array, .include? should stop as soon as it finds a match and there's no overhead of calling a block; so, .include? should be quicker but the performance differences will probably be pretty irrelevant unless you have a massive array. I'd go with whichever one reads best for you.


Another possibility is the any? or none? methods, and using the nil? method:

irb(main):005:0> [1, nil, 2, 'a'].any?(&:nil?)
=> true
irb(main):006:0> [1, nil, 2, 'a'].none?(&:nil?)
=> false

The &:foo syntax works to replace anything like: list.each() {|x| x.foo()}


Are you playing Golf?

That's about as short and direct as you are gonna get. Personally I'd prefer a slightly more verbose way:

[...].all? {|x| !x.nil? }


I suppose you could do::

!list.any?(&:nil?)

But I find that less direct than your original code. Fewer characters, though, and if you dislike blocks this hides the block in the &:symbol

[Well, your original code has a problem which is that {|x| x } evaluates as false for both nil and false values. If you really want the block {|x| !x.nil?} ]


Almost the same as mu is too short, and I don't think mine any better than it, but just another variant:

![1, nil, 2, 'a'].index(nil)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜