Menu
CoddyTech

Defaults and Keywords

Lesson 13 of 48 in Coddy's Ruby for JavaScript Developers course.

JavaScript often emulates named arguments with an options object and destructuring defaults. Ruby keyword arguments have their own calling convention, and Ruby 3 distinguishes them from a positional hash. A double splat explicitly expands keyword arguments. Defaults are applied only to omitted arguments according to each language's rules.

JavaScript: complete program

function border(text, {mark = "."} = {}) { return mark + text + mark; }
console.log(border("x"));
console.log(border("x", {mark: "!"}));

Ruby: complete program

def border(text, mark: ".")
  mark + text + mark
end
puts border("x")
puts border("x", mark: "!")
challenge icon

Challenge

Easy

Define 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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Ruby for JavaScript Developers

Practice on your own: Online Ruby compiler