0
0
Rubyprogramming~15 mins

Parameters with default values in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Parameters with default values
📖 Scenario: You are creating a simple greeting system for a website. Sometimes users provide their name, and sometimes they don't. You want to write a method that can greet users by name if given, or greet them with a generic message if no name is provided.
🎯 Goal: Build a Ruby method called greet that takes one parameter name with a default value. The method should return a greeting message using the given name or a default greeting if no name is given.
📋 What You'll Learn
Create a method called greet with one parameter name that has a default value of "Guest".
Inside the method, return a string that says "Hello, <name>!" where <name> is the parameter value.
Call the greet method twice: once without any argument, and once with the argument "Alice".
Print the results of both method calls.
💡 Why This Matters
🌍 Real World
Default parameters are useful when you want to make your methods flexible and easy to use without always requiring all information.
💼 Career
Understanding default parameters helps you write cleaner, more maintainable code in Ruby, which is important for many programming jobs.
Progress0 / 4 steps
1
Create the greet method with a name parameter
Write a method called greet that takes one parameter named name. Do not add a default value yet.
Ruby
Need a hint?

Use def to define the method and include name inside parentheses.

2
Add a default value "Guest" to the name parameter
Modify the greet method so that the parameter name has a default value of "Guest".
Ruby
Need a hint?

Set the default value by writing name = "Guest" inside the parentheses.

3
Return a greeting message using the name parameter
Inside the greet method, return a string that says "Hello, <name>!" where <name> is the value of the name parameter. Use string interpolation.
Ruby
Need a hint?

Use "Hello, #{name}!" to create the greeting string.

4
Call greet with and without an argument and print the results
Call the greet method twice: once without any argument, and once with the argument "Alice". Print both results using puts.
Ruby
Need a hint?

Use puts greet and puts greet("Alice") to print the greetings.