Menu
CoddyTech

Nil and Optional Values

Lesson 22 of 48 in Coddy's Ruby for Python Developers course.

Python None and Ruby nil represent absence, but they are not interchangeable with numeric zero. Nil is falsey in Ruby; zero is truthy. Ruby safe navigation invokes a method only when the receiver is not nil. It does not suppress every exception and does not skip a receiver whose value is false. Use explicit nil? when you need to preserve false as a valid result. A default based on || replaces both nil and false, which may be too broad.

Python: complete program

word = None
print("missing" if word is None else word.upper())
zero = 0
print(zero if zero is not None else 9)

Ruby: complete program

word = nil
puts(word&.upcase || "missing")
puts(0 || 9)
challenge icon

Challenge

Easy

Read a name followed by zero or more name=value pairs, each value a nonnegative integer. Return that name's last assigned value, including zero; missing names return absent.

Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.

Your code goes in exercise.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'exercise'
def check(value)
  raise 'Public API check failed' unless value
end

puts solve(STDIN.read)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Ruby for Python Developers

Practice on your own: Online Ruby compiler