CodeNewbie Community ๐ŸŒฑ

Cover image for 49 Days of Ruby: Day 18 - Parameters
Ben Greenberg
Ben Greenberg

Posted on • Originally published at dev.to on

49 Days of Ruby: Day 18 - Parameters

Welcome to day 18 of the 49 Days of Ruby! ๐ŸŽ‰

Methods as we discussed yesterday are building blocks of your code. Parameters are the inputs for your methods!

This lesson today is going to be a quick one, as we're going to briefly expand upon yesterday and fill in an important detail about how to use parameters.

Parameters in Ruby

Let's say I had the following method:

def coffee
  puts "Here's your coffee!"
end

Enter fullscreen mode Exit fullscreen mode

If I ran this method, the output would be Here's your coffee!. What if I also wanted to output the customer's name? I could create a method for each customer:

def coffee_for_sarah
  puts "Here's your coffee, Sarah!"
end

def coffee_for_joe
  puts "Here's your coffee, Joe!"
end

Enter fullscreen mode Exit fullscreen mode

That does not feel very scalable though. A method for each customer will quickly become impossible to manage.

There is a better way:

def coffee(customer)
  puts "Here's your coffee, #{customer}"
end

Enter fullscreen mode Exit fullscreen mode

Now, I can invoke it like the following:

> coffee("Jill")

# => "Here's your coffee, Jill!"

Enter fullscreen mode Exit fullscreen mode

We learned about string interpolation earlier on in this journey. It's where you combine a variable with a string to produce a new unified result.

In this case, we build our method of #coffee with a parameter of customer. We are basically instructing our method to expect a data input. We don't tell the method anything about what the data is, only that it should be there.

That's a parameter!

Try building parameters with methods on your own and share your learning!

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.

Top comments (0)