Lesson 2
Functions with Parameters - Customizing Behavior
Welcome to Functions with Parameters in Ruby

Building on your knowledge of defining functions, we are now ready to explore how to make them even more powerful. The lesson dives into functions with parameters. This feature will allow you to customize your functions to handle different inputs, making them more flexible and efficient. Let's embark on this new adventure!

What You'll Learn

In this lesson, you'll learn:

  • How to define functions that accept parameters in Ruby.
  • The syntax for incorporating parameters into your functions.
  • How to call these functions with different arguments.

Here is a quick example to illustrate:

Ruby
1# Function to greet by name 2def greet_by_name(name) 3 puts "Hello, #{name}! Ready for your next adventure?" 4end 5 6# Calling the function with an argument 7greet_by_name("Alice")

In this example, we define a function greet_by_name that accepts a parameter name. When we call this function with the argument "Alice", it prints Hello, Alice! Ready for your next adventure?. We can call this function with different names to greet various people.

We can have multiple parameters in a function, separated by commas. Here's an example:

Ruby
1def meet(name1, name2) 2 puts "#{name1} and #{name2} met Cosmo" 3end 4 5meet("Alice", "Bob") # Output: Alice and Bob met Cosmo 6meet "Charlie", "Daisy" # Output: Charlie and Daisy met Cosmo

In this example, the meet function accepts two parameters name1 and name2. When we call this function with different arguments, it prints the names of the people who met Cosmo.

Notice, that we used parentheses in the first call and omitted them in the second call. Both ways are valid in Ruby when calling a function with parameters. Although, both ways are valid, it's a good practice to use parentheses when calling functions with parameters to make the code more readable.

Why It Matters

Understanding functions with parameters is crucial because it makes your code adaptable and less repetitive. By defining functions that accept parameters, you can reuse the same code with different inputs, saving time and effort.

Through this, we achieve a cleaner and more efficient way to handle multiple scenarios with the same piece of code. This approach not only saves time but also enhances the maintainability of your programs.

Excited to get hands-on with these concepts? Let's move on to the practice section and start coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.