Menu
CoddyTech

Nil and Optional Values

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

R distinguishes NULL, empty vectors and NA, which represent different situations. Ruby nil is an object often used for absence, and safe navigation skips only nil. Zero is truthy in Ruby and || also replaces false. Map R missing states deliberately instead of translating every NA or zero-length value into a truthiness fallback.

R: complete program

text <- "";chosen <- if(is.null(text)) "guest" else text;cat(nchar(chosen),"\n",sep="")

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

Practice on your own: Online Ruby compiler