开发者

Built in method for testing either nil or empty array?

开发者 https://www.devze.com 2023-02-27 02:56 出处:网络
开发者_运维技巧How can I tell if an array is either empty or nil?Without Rails or ActiveSupport,

开发者_运维技巧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

0

精彩评论

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