Built in method for testing either nil or empty array?
开发者_运维技巧How can I tell if an array is either empty or nil?
Without Rails or ActiveSupport,
array.to_a.empty?
There's no built-in Ruby method that does this, but ActiveSupport
's blank
does:
>> require "active_support/core_ext/object/blank" #=> true
>> nil.blank? #=> true
>> [].blank? #=> true
You can just use the Array#empty? and Object#nil? methods in conjunction with an OR.
arr.nil? || arr.empty?
This will return true of array is empty or the array value is nil.
To check whether array is empty one can use 'empty?' inbuilt method as follows,
array.empty? # returns true/false
To check whether array is nil (If not initialized or set to nil)
array.nil? # returns true/false
精彩评论