What values are considered truthy and falsy in Ruby, and how do nil and false differ?
Last updated
In Ruby only two values are falsy: false and nil. Everything else is truthy, including 0, empty strings, and empty arrays.
Falsy values: Only
nilandfalseevaluate as false in conditionals.Truthy values: Everything else, including
0,"", and[](unlike many other languages).How
nilandfalsediffer:nilis an instance ofNilClassrepresenting absence of value;falseis an instance ofFalseClassrepresenting a real boolean.Use
.nil?to test specifically for nil, since both look falsy in anif.
Practical tip: To distinguish "missing" from "explicitly false", compare with
==or usenil?rather than relying on truthiness.
- https://www.ruby-lang.org/en/documentation/faq/6/
- https://medium.com/@fhyfr/ensuring-boolean-values-in-ruby-the-power-of-double-negation-aad2630493e6
- https://www.freecodecamp.org/news/data-types-in-ruby-true-false-and-nil-explained-with-examples/
- https://docs.ruby-lang.org/en/master/syntax/control_expressions_rdoc.html
- https://dev.to/baweaver/understanding-ruby-memoization-2be5
- https://gist.github.com/jfarmer/2647362
- https://dev.to/wrschneider/opinions-on-truthiness-across-languages