Truthiness: only false and nil

Contents
Only false and nil are falsy
Zero is truthy
Empty is truthy
Use it for guards

Only false and nil are falsy

Every Ruby value counts as true in a condition except two: false and nil. nil means no value, the answer you get when something is missing.

Both lines below stay silent because their conditions are falsy, so only the last line prints:

puts "hi" if false puts "hi" if nil puts "done"

done

Zero is truthy

In some languages zero behaves like false, but not in Ruby. The number zero is an ordinary truthy value, so a counter reaching zero still passes the check.

if 0 puts "zero is truthy" end

zero is truthy

Empty is truthy

Empty values are truthy as well. An empty string and an empty array both pass the check: only false and nil can stop a condition.

if "" puts "empty string is truthy" end if [] puts "empty array is truthy" end

empty string is truthy
empty array is truthy

Use it for guards

Truthiness shines in small guard lines that handle the missing case first. Ask whether a value is nil, print a fallback, and let the rest of the code assume a real value.

name = nil puts "guest" if name.nil?

guest

Flip the variable to a real string and the guard stays silent. The next lesson builds full if and else branches on top of this idea.

Next: Conditions

Article author: Arthur Isaev

Related articles
Ruby
Ruby course: zero to hero in 50 lessons
What is Ruby and where it runs
Install Ruby and check the version
irb: the interactive shell
Your first Ruby script
Variables
Numbers
Strings
Symbols
Truthiness: only false and nil
Conditions
Loops
Arrays
Hashes
Ranges
Methods
Blocks, procs, lambdas
String tools
Files and IO
Exceptions
Modules and mixins
Classes and objects
Inheritance
Enumerables
Duck typing and core idioms
Gems and Bundler
Testing with Minitest
Debugging
Encodings
Time and date
JSON and YAML
HTTP clients
Sockets
REST APIs
puts, print and p
Metaprogramming
Enumerators
Pattern matching
Arguments: splats and kwargs
Rake tasks
Environment and CLI
Logging
CSV
ERB templates
WEBrick server
Rails in one lesson
Capstone: todo CLI
Capstone: JSON API
Performance
Modern Ruby tour
Hero roadmap: the whole course on one page
Install Ruby on Windows 11
Install Ruby on Ubuntu
Install Ruby on Rocky Linux
Install Ruby on macOS
Install Ruby on FreeBSD
Ruby in Docker
Threads and fibers

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: