What is the difference between nil and false in Ruby?
Overview
Everything is regarded as an object in Ruby.
Ruby’s built-in data types are false and nil.
|
|
|
|
|
|
|
|
Note: In Ruby,
true,false, andnilrefer to objects rather than integers. Thetrueandfalseare not the same as 0, andtrueandnilare not the same as 1.
Special case
When Ruby needs a boolean value, nil is treated as false, and values other than nil or false are treated as true.
students = ["Jeery", "Tom", "Eddie"]#this will print student at index 0puts students[0]#nil#this will output nothing since index doesnot existputs students[4]#this will output the class that belongs to nilputs students[4].class#false#this will output false since both names does not matchputs students[0] == students[1]#this will output the class that belongs to falseputs (students[0] == students[1]).class#special case#nil treated as falseJeery = nilif Jeeryputs "Jeery is present"elseputs "Jeery is absent"end#false treated as falseTom = falseif Tomputs "Tom is present"elseputs "Tom is absent"end
Explanation
- Line 4: We print the student at index
0. - Line 6–10: We print the
nilandnilclass. - Line 12–16: We print the
falseandfalseclass. - Line 19–34: We print the special case, when the
nilis also treated asfalsefollowed by the behavior of actualfalse.