Method Parameters

You may have noticed that some methods (such as gets, reverse, to_s, and so on) can just be called on an object. However, other methods (such as +, -, puts…) take parameters to tell the object how to do the method. For example, you wouldn’t just say 5+, right? You’re telling 5 to add, but you aren’t telling it what to add.

To add a parameter to say_moo (let’s say, the number of moos), we would do the following:

def​ say_moo number_of_moos
puts ​'mooooooo...'​*number_of_moos
end
say_moo 3
puts ​'oink-oink'
# This last line should give an error
# because the parameter is missing...
say_moo
mooooooo...mooooooo...mooooooo...
oink-oink
example.rb:1:in `say_moo': wrong number of arguments (0 for 1) (ArgumentError)
from example.rb:10:in `<main>'

number_of_moos is a variable that points to the parameter passed in. I’ll say that again, but it’s a little confusing: number_of_moos is a variable that points to the parameter passed in. So, if I type say_moo 3, then the parameter is 3, and the variable number_of_moos points to 3.

As you can see, the parameter is now required. After all, what is say_moo supposed to multiply 'mooooooo...' by if you don’t give it a parameter? Your poor computer has no idea.

If objects in Ruby are like nouns in English and methods are like verbs, then you can think of parameters as adverbs (like with say_moo, where the parameter told us how to say_moo) or sometimes as direct objects (like with puts, where the parameter is what gets putsed).

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

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