Default argument values

We'll finish up our discussion on Ruby method arguments by discussing default values. There are many times when you'll want to supply default values for an argument and Ruby let's you implement this functionality quite easily.

Let's take the example of building a method that streams movies. We'll need the user to tell the method which movie to watch; however, we don't want them to have to enter in the language for the movie unless it's other than English. In cases like this, we can use the default values with this syntax:

def stream_movie title:, lang: lang = 'English' 
puts title
puts lang
end

stream_movie title: 'The Fountainhead'

As you can see, this works properly and prints out English as the language because we declared it as a default language.

Now if we want to watch a movie in Spanish, we can optionally pass in the lang argument into the method call:

stream_movie title: 'The Fountainhead', lang: 'Spanish' 

I hope that this has been a helpful guide to how you can use method arguments in Ruby. In the next section, we'll walk through the splat and optional argument components that Ruby allows.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.152.157