Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ### Method argument syntax
- Methods can be written with or without parenthesis. Methods can be called with arguments passed in with or without parenthesis, regardless of how the method was defined.
- #### Method syntax with parenthesis
- ```ruby
- def full_name(first_name, last_name)
- first_name + " " + last_name
- end
- ```
- Calling method with parenthesis:
- ```
- $ puts full_name("Johnny", "Apples")
- Johnny Apples
- => nil
- ```
- #### Method syntax without parenthesis
- ```ruby
- def full_name first_name, last_name
- first_name + " " + last_name
- end
- ```
- Calling method without parenthesis:
- ```
- $ puts full_name "Johnny", "Apples"
- Johnny Apples
- => nil
- ```
- ### Method syntax with named arguments
- Using named arguments allow you to pass arguments to a method in any order without effecting the result of the method, and it's much more explicit. Can also be used with or without parenthesis.
- ```ruby
- def print_address city:, state:, zip:
- puts city
- puts state
- puts zip
- end
- ```
- Calling `print_address` in defined order:
- ```
- $ print_address city: "New York", state: "NY", zip: 10014
- New York
- NY
- 10014
- => nil
- ```
- Calling `print_address` in alternate order:
- ```
- $ print_address zip: 10014, city: "New York", state: "NY"
- New York
- NY
- 10014
- => nil
- ```
- ### Method syntax with named arguments and default values
- Default values can be used to set a default parameter which can be overridden on method call.
- ```ruby
- def book title:, language: "EN"
- puts title
- puts language
- end
- ```
- Calling `book` with a default value:
- ```
- $ book title: "The Mist", language: "EN"
- The Mist
- EN
- => nil
- ```
- Calling `book` without defining a value:
- ```
- $ book title: "The Mist"
- The Mist
- EN
- => nil
- ```
- Calling `book` and overriding the default value:
- ```
- $ book title: "The Idiot", language: "RU"
- The Idiot
- RU
- => nil
- ```
Add Comment
Please, Sign In to add comment