Nil and Optional Values
Lesson 22 of 48 in Coddy's Ruby for Java Developers course.
Java null is not an object and a dereference can raise NullPointerException. Ruby nil is an object used for absence; safe navigation skips calls only on nil. Java Optional can make absence explicit but is a library abstraction, not identical to Ruby nil. A numeric zero is a present value in both examples.
Java: complete program
import java.util.*;
public class Main {
public static void main(String[] args) {
String word = null;
System.out.println(word == null ? "missing" : word.toUpperCase(Locale.ROOT));
Integer zero = 0;
System.out.println(zero == null ? 9 : zero);
}
}Ruby: complete program
word = nil
puts(word&.upcase || "missing")
puts(0 || 9)Challenge
EasyRead 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Ruby for Java Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip4Mutation and Errors
Mutation and AliasesNil and Optional ValuesExceptions and ValidationEnsure and CleanupRecap: Safe Ratio2Flow and Methods
Conditional ValuesCase and RangesLoops and Early ExitMethods and ReturnsDefaults and KeywordsRecap: Sensor Run5Objects and State
Modules as NamespacesClasses and InstancesReaders and WritersValidated ConstructionRecap: Wallet8Lending Desk Project
Lending Desk: CatalogLending Desk: BorrowPractice on your own: Online Ruby compiler