Ruby の empty? と nil? について調べた
Ruby
Published: 2019-04-07

やったこと

Ruby で empty? と nil? について調べました。

確認環境

$ ruby -v
ruby 2.2.7p470 (2017-03-28 revision 58194) [x86_64-darwin16]

調査

test.rb

abc = [
    nil,
    '',
    false,
    0,
    [],
]

abc.each_with_index do |v, i|
    printf("check %d\n", i)
    begin
        if v.nil?
            p 'abc is nil'
        else
            p 'abc is not nil'
        end
    rescue => error
        p error
    end

    begin
        if v.empty?
            p 'abc is empty'
        else
            p 'abc is not empty'
        end
    rescue => error
        p error
    end
end

実行結果

$ ruby test.rb

check 0
"abc is nil"
#<NoMethodError: undefined method `empty?' for nil:NilClass>
check 1
"abc is not nil"
"abc is empty"
check 2
"abc is not nil"
#<NoMethodError: undefined method `empty?' for false:FalseClass>
check 3
"abc is not nil"
#<NoMethodError: undefined method `empty?' for 0:Fixnum>
check 4
"abc is not nil"
"abc is empty"