Bird
Raised Fist0
Rubyprogramming~10 mins

Keyword arguments in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Keyword arguments
Define method with keyword args
↓
Call method with keywords
↓
Match call keywords to params
↓
Execute method body using keywords
↓
Return result or output
The method is defined with named keyword arguments. When called, the keywords match parameters, then the method runs using those values.
Execution Sample
Ruby
def greet(name:, age:)
  "Hello, #{name}! You are #{age} years old."
end

puts greet(name: "Alice", age: 30)
Defines a method with keyword arguments and calls it with named values to print a greeting.
Execution Table
StepActionKeyword ArgumentValueResult/Output
1Define method greet with keywordsname, agenone yetMethod ready
2Call greet with keywordsname"Alice"Waiting for method body
3Call greet with keywordsage30Waiting for method body
4Match keywords to parametersname"Alice"name = "Alice"
4Match keywords to parametersage30age = 30
5Execute method bodyname, age"Alice", 30"Hello, Alice! You are 30 years old."
6puts outputs stringnonenoneHello, Alice! You are 30 years old.
💡 Method finishes after returning the greeting string and puts prints it.
Variable Tracker
VariableStartAfter CallAfter MatchFinal
nameundefinedpassed "Alice""Alice""Alice"
ageundefinedpassed 303030
Key Moments - 3 Insights
Why do we write name: and age: in the method definition?
Because these define keyword arguments that must be passed by name when calling the method, as shown in execution_table rows 1 and 2.
What happens if we call greet without one keyword argument?
Ruby will raise an error because the method expects all keyword arguments to be provided, as implied by the matching step in execution_table row 4.
Can we change the order of keyword arguments when calling the method?
Yes, because keywords match by name, not position, so order does not matter (see execution_table rows 2 and 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'age' after matching keywords to parameters?
Aundefined
B"Alice"
C30
Dnil
💡 Hint
Check execution_table row 4 where 'age' is matched to 30.
At which step does the method actually produce the greeting string?
AStep 2
BStep 5
CStep 4
DStep 6
💡 Hint
Look for the step where method body executes and returns the string (execution_table row 5).
If we call greet(age: 30, name: "Alice") instead, what changes in the execution_table?
AThe matching order of keywords changes but final values stay the same
BThe method will error because order changed
CThe output string changes
DThe method ignores the age argument
💡 Hint
Keyword arguments match by name, so order does not affect final variable values (see key_moments answer 3).
Concept Snapshot
def method_name(keyword1:, keyword2:)
  # use keyword1 and keyword2 inside
end

Call with method_name(keyword1: value1, keyword2: value2)

- Keywords must be named when calling
- Order does not matter
- Missing keywords cause errors
Full Transcript
This example shows how Ruby methods can use keyword arguments. The method greet is defined with two keywords: name and age. When calling greet, we pass values by naming them, like name: "Alice" and age: 30. Ruby matches these names to the parameters inside the method. Then the method uses these values to build a greeting string. Finally, puts prints the greeting. Keyword arguments help make code clearer by naming what each value means. They also allow arguments in any order but require all keywords to be given.

Practice

(1/5)
1. What is the purpose of keyword arguments in Ruby methods?
easy
A. To convert all arguments into strings automatically
B. To force all arguments to be passed in order
C. To make arguments optional without default values
D. To allow passing arguments by name for clarity and flexibility

Solution

  1. Step 1: Understand keyword arguments

    Keyword arguments let you pass values to a method by naming them, not just by position.
  2. Step 2: Identify the benefit

    This makes code clearer and lets you skip or reorder arguments easily.
  3. Final Answer:

    To allow passing arguments by name for clarity and flexibility -> Option D
  4. Quick Check:

    Keyword arguments = named, clear, flexible [OK]
Hint: Keyword arguments are named for clarity and order freedom [OK]
Common Mistakes:
  • Thinking keyword arguments force order
  • Confusing keyword arguments with positional arguments
  • Assuming keyword arguments convert types automatically
2. Which of the following is the correct syntax to define a method with keyword arguments in Ruby?
easy
A. def greet(name =>, age =>); puts "Hello #{name}, you are #{age}"; end
B. def greet(name, age); puts "Hello #{name}, you are #{age}"; end
C. def greet(name:, age:); puts "Hello #{name}, you are #{age}"; end
D. def greet(name =:, age =:); puts "Hello #{name}, you are #{age}"; end

Solution

  1. Step 1: Review Ruby keyword argument syntax

    Keyword arguments are defined with a colon after the argument name, like name:.
  2. Step 2: Check each option

    def greet(name:, age:); puts "Hello #{name}, you are #{age}"; end uses correct syntax with name: and age:. Others use invalid symbols or positional arguments.
  3. Final Answer:

    def greet(name:, age:); puts "Hello #{name}, you are #{age}"; end -> Option C
  4. Quick Check:

    Keyword args use colon after name [OK]
Hint: Keyword args end with colon in method definition [OK]
Common Mistakes:
  • Using => instead of : for keyword arguments
  • Defining keyword arguments without colons
  • Confusing positional and keyword argument syntax
3. What will be the output of the following Ruby code?
def info(name:, age: 30)
  "Name: #{name}, Age: #{age}"
end

puts info(name: "Alice")
medium
A. Name: Alice, Age: 30
B. Name: Alice, Age:
C. ArgumentError: missing keyword: age
D. Name: , Age: 30

Solution

  1. Step 1: Analyze method parameters

    The method info has a required keyword argument name: and an optional keyword argument age: with default 30.
  2. Step 2: Check method call

    The call passes name: "Alice" but no age, so default 30 is used.
  3. Final Answer:

    Name: Alice, Age: 30 -> Option A
  4. Quick Check:

    Default keyword argument used when missing [OK]
Hint: Missing keyword uses default if provided [OK]
Common Mistakes:
  • Expecting error when optional keyword is missing
  • Confusing positional defaults with keyword defaults
  • Ignoring default values in keyword arguments
4. Identify the error in the following Ruby method call:
def order(item:, quantity:)
  "Order: #{quantity} x #{item}"
end

puts order(quantity: 3, "apple")
medium
A. ArgumentError: missing keyword: item
B. SyntaxError due to positional argument after keyword argument
C. No error, prints 'Order: 3 x apple'
D. TypeError: wrong argument type String (expected Symbol)

Solution

  1. Step 1: Examine method call arguments

    The call uses quantity: 3 (keyword) then "apple" (positional).
  2. Step 2: Understand Ruby argument rules

    In Ruby, positional arguments cannot come after keyword arguments in a call; this causes a syntax error.
  3. Final Answer:

    SyntaxError due to positional argument after keyword argument -> Option B
  4. Quick Check:

    Positional args must come before keyword args [OK]
Hint: Positional args cannot follow keyword args in calls [OK]
Common Mistakes:
  • Passing positional argument after keyword argument
  • Assuming Ruby allows mixed order without error
  • Confusing missing keyword with syntax error
5. Given this method:
<pre>def build_profile(name:, age:, city: "Unknown", **extras) profile = {name: name, age: age, city: city} profile.merge!(extras) profile end What will be the result of build_profile(name: "Bob", age: 25, hobby: "guitar", pet: "dog")?
hard
A. {:name=>"Bob", :age=>25, :city=>"Unknown", :hobby=>"guitar", :pet=>"dog"}
B. {:name=>"Bob", :age=>25, :city=>"Unknown"}
C. ArgumentError: unknown keyword: hobby
D. {:name=>"Bob", :age=>25, :city=>"Unknown", :extras=>{:hobby=>"guitar", :pet=>"dog"}}

Solution

  1. Step 1: Understand method parameters

    The method requires name and age, has optional city with default, and collects extra keyword arguments into extras.
  2. Step 2: Analyze method call

    The call passes name, age, and extra keywords hobby and pet. These extras are merged into the profile hash.
  3. Step 3: Determine final hash

    The returned hash includes all keys: name, age, default city, plus hobby and pet from extras.
  4. Final Answer:

    {:name=>"Bob", :age=>25, :city=>"Unknown", :hobby=>"guitar", :pet=>"dog"} -> Option A
  5. Quick Check:

    Extras merged into hash with defaults [OK]
Hint: Use **extras to capture and merge extra keyword args [OK]
Common Mistakes:
  • Expecting error on unknown keywords with **extras
  • Forgetting to merge extras into profile
  • Assuming extras stored under :extras key
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard