Lesson content is currently in draft form.
The methods we’ve learned so far are simple:
1 2 3 4 5 |
|
Arguments
If you’ve ever used a word-processor, you’ve probably used the “Find-and-Replace” function. Ruby strings have the sub
and gsub
methods (‘substitute’ and ‘global substitute’):
1 2 |
|
1 2 |
|
The sub
and gsub
methods can be said to require 2 arguments. Think of arguments as the input to the method. In this example, the first argument is the string to be replaced. The second argument is what to replace it with.
About parentheses
In the sub
and gsub
methods above, we used parentheses to enclose the arguments. Unlike many other languages, Ruby makes these optional:
1 2 |
|
1 2 |
|
As you start out, I recommend keeping the parentheses. They may be a pain to type, but they can add readability to your code.
Exercise
In the last chapter, we added a bunch of strings together to form a URL:
1 2 3 |
|
Not only is this a pain to read and write, it’s prone to mistakes:
1 2 3 4 5 6 7 |
|
Look at the documentation for the File.join
method and see if you can come up with a better way to compose the URL.
Answer
1 2 3 4 5 6 |
|
The point of this chapter is not to memorize these method names, but to be familiar with the pattern of methods taking in arguments (i.e. inputs) and returning a value.
We’ll be using File.join
, sub
, and gsub
later on, but if you forget their names or what they do, you can look them up easily enough.