Menu
CoddyTech

Nil and Optional Values

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

Luau nil represents missing data and cannot be retained as an ordinary stored table value. Ruby nil is an object and can occupy array slots or hash values. Ruby &. skips only nil, while || also falls back for false, as Luau or does. Use explicit absence checks when false is a legitimate result.

Luau: complete program

local text="";local chosen=text;if chosen==nil then chosen="guest" end;print(#chosen)

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 Luau Developers

Practice on your own: Online Ruby compiler