What's the way to check if all the elements in

2019-08-04 13:26发布

This question already has an answer here:

I would like to know if there's anything except nil values in an array.

arr = [nil, nil, nil, nil] # => true
arr = [nil, 45, nil, nil] # => false

There could be any values of any types (not only 45).

标签: arrays ruby
3条回答
疯言疯语
2楼-- · 2019-08-04 14:03

Use the Enumerable#all? method:

p arr.all? { |x| x.nil? }

Or

p arr.all?(&:nil?)

As @Stefan suggested,

 p arr.all?(NilClass) #works only for Ruby 2.5
查看更多
冷血范
3楼-- · 2019-08-04 14:10

you could do arr.compact.empty?, compact gets rid of all the nil for you

you could read here at ruby guides to find about all the methods on Array class

查看更多
姐就是有狂的资本
4楼-- · 2019-08-04 14:12

You can also use #any? method for array

[nil, 45].any?
=> true
[nil, nil].any?
=> false

From the documentation:

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.

Note: This won't work if false boolean values are present.

[nil, false].any?
=> false # It should return `true`

Other options would be:

arr = [nil, nil, 45]
arr.count(nil) == arr.length
=> false

(arr - [nil]).empty?
=> false
查看更多
登录 后发表回答