Defaults and Keywords
Lesson 13 of 48 in Coddy's Ruby for C Developers course.
Standard C has no default or keyword parameters; wrappers and option structs can express similar contracts. Ruby provides positional defaults and keyword arguments directly. Ruby 3 distinguishes a positional hash from keyword arguments, so use explicit double-splat expansion when forwarding keywords. Preserve missing-versus-zero distinctions in option values.
C: complete program
#include <stdbool.h>
#include <stdio.h>
struct Options { bool has_repetitions; int repetitions; };
static int repetitions(struct Options options) {
return options.has_repetitions ? options.repetitions : 2;
}
int main(void) {
struct Options missing = {false, 0};
struct Options zero = {true, 0};
printf("%d:%d\n", repetitions(missing), repetitions(zero));
return 0;
}Ruby: complete program
def border(text, mark: ".")
mark + text + mark
end
puts border("x")
puts border("x", mark: "!")Challenge
EasyDefine charge(units, rate: 4, discount: 0) returning units*rate-discount. Input has units alone, units rate, or units rate discount. solve must use defaults for omitted fields.
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, pricing.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'exercise'
require_relative 'pricing'
def check(value)
raise 'Public API check failed' unless value
end
check(charge(7) == 28)
check(charge(7, discount: 3) == 25)
check(charge(2, rate: 9, discount: 1) == 17)
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 C 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