Symbols and Keys
Lesson 7 of 48 in Coddy's Ruby for Java Developers course.
Java has no direct equivalent of Ruby symbol literals; strings or enums often represent named choices. Java maps use equals/hashCode semantics for keys, and two equal string keys update one entry. Ruby a symbol and same-spelled string are distinct keys. Java string interning is not a replacement for understanding Ruby symbols.
Java: complete program
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String,Integer> data = new HashMap<>();
data.put("mode", 1);
data.put("mode", 2);
System.out.println(data.size());
System.out.println(data.get("mode"));
}
}Ruby: complete program
data = {mode: 1, "mode" => 2}
puts data.length
puts data[:mode]Challenge
EasyRead one command: start, stop or any other text. Look up its symbol in a fixed table: start maps to 1, stop maps to 0. Unknown commands return -1.
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 Slip2Flow 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