Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 21 / 68

Writing nil-Safe Code

In this lesson you will learn nil-safe code in Ruby so missing data can be handled safely. This is for anyone searching for "Ruby nil safe how to use".

Ruby uses nil to represent the absence of a value. || lets you fall back to the right-hand value when the left is nil or false. It is a convenient way to give a possibly-missing value a safe default.

The sample code prints a replacement string with || "No address set" when user[:address] is nil. This form is used constantly as the safe way to read from a hash when a key may not exist.

A common stumbling block for beginners is a mismatch with the sense of "falsy" from other languages. In Ruby only false and nil count as false, so 0 and an empty string are true - especially confusing if you are used to JavaScript.

Combined with unless, you can write "if it is not nil" almost like plain English. Real Ruby code always has to allow for parts of an API response coming back nil.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)