Menu
CoddyTech

Defaults and Keywords

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

GDScript supports trailing positional defaults but not ordinary keyword-call arguments. Ruby supports both positional defaults and keyword parameters, and Ruby 3 distinguishes positional hashes from keywords. A double splat forwards keyword entries deliberately. Use defaults to express missing inputs without conflating an explicit zero or false with omission. Repeated Ruby definitions replace the method rather than adding overloads.

GDScript: complete program

extends SceneTree

func repeat_name(name: String, count: int = 2) -> String:
	var copies = PackedStringArray()
	for index in range(count):
		copies.append(name)
	return ",".join(copies) if count > 0 else "none"

func _init():
	print(repeat_name("Ada"))
	print(repeat_name("Ada", 0))
	quit()

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

Practice on your own: Online Ruby compiler