|
| 1 | +#!usr/bin/env ruby |
| 2 | + |
| 3 | +# Defines a methods with multiple arguments. |
| 4 | +def volume(x, y, z) |
| 5 | + x * y * z |
| 6 | +end |
| 7 | + |
| 8 | +puts volume(2,3,4) |
| 9 | +puts volume(5,7,8) |
| 10 | +puts volume(42,86,22) |
| 11 | + |
| 12 | +# The order of arguments passed in matters. |
| 13 | +def introduction(greeting, name) |
| 14 | + puts "#{greeting}, #{name}." |
| 15 | +end |
| 16 | + |
| 17 | +# Here the name is passed in first, resulting on a different output than expected. |
| 18 | +introduction("Yoda","I am") # "Yoda, I am." |
| 19 | +introduction("I am","Groot") # "I am, Groot." |
| 20 | + |
| 21 | +# Arguments can be optional, any object can be passed as a default value. |
| 22 | +def greet(greeting="Hello", name="World") |
| 23 | + puts "#{greeting}, #{name}" |
| 24 | +end |
| 25 | + |
| 26 | +# Calls greet with no arguments so default ones are used. |
| 27 | +# As per convention the parentheses are kept. |
| 28 | +greet() |
| 29 | + |
| 30 | +welcome_options = { |
| 31 | + name: "Geralt", |
| 32 | + punctuation: "..." |
| 33 | +} |
| 34 | + |
| 35 | +# A hash with optional arguments is passed, allowing more flexibility. |
| 36 | +# Each expected key is checked for a value inside the method. |
| 37 | +def welcome(greeting, options={}) |
| 38 | + name = options[:name] || 'friend' |
| 39 | + punct = options[:punctuation] || '!' |
| 40 | + greeting + ' ' + name + punct |
| 41 | +end |
| 42 | + |
| 43 | +# The greeting arg is always passed in but the options hash is optional. |
| 44 | +puts welcome("It's you,", welcome_options); |
| 45 | +puts welcome("Hello"); |
0 commit comments