Optional arguments

Last on our list of method arguments is the ability to pass optional arguments to a method. There are a number of times when you want flexibility with what types of data you pass to methods, and that's where optional arguments can come in handy.

Let's imagine that we're creating an invoice method. Our implementation needs to be flexible because some customers provide different data than others. We can accommodate this type of behavior using code like this:

def invoice options={} 
puts options[:company]
puts options[:total]
puts options[:something_else]
end

invoice company: "Google", total: 123, state: "AZ"

When we run this program, you can see some interesting behavior. We're using the options hash in our method declaration. The options term is not required; you could use any word, but options is considered as a standard term to use:

From this point, we can use the syntax such as options[:company] to grab the parameters that we want to use. There is a clear mapping between the name we call inside the method and the named argument we pass when we call the method. Also of note (and warning) is that this type of tool can cause silent bugs in your program. Do you notice how I attempted to print out options[:something_else] and I also passed an additional argument of state: "AZ" into the program? However, these items did not throw an error. This means that you need to be careful when you use optional arguments because they won't fail, they simply won't do anything.

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

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