Last active
August 29, 2015 14:07
-
-
Save KazW/609573f0062617e2c249 to your computer and use it in GitHub Desktop.
2.1.3 method declaration syntax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# All of the following method declarations are equivalent. (They all have the same result) | |
# The only difference is in how they are called. | |
some_data = {required_argument: 'bob', optional_argument: 'dole'} | |
# Pre 2.1.3 style | |
def some_method(required_argument, optional_requirement = nil) | |
p [required_argument, optional_argument] | |
end | |
some_method()# => ArgumentError: wrong number of arguments (0 for 1..2) | |
some_method('bob')# => "['bob',nil]" | |
some_method('bob', 'dole')# => "['bob','dole']" | |
some_method(some_data)# => "[{required_argument: 'bob', optional_argument: 'dole'},nil]" | |
# Pre 2.1.3 style using named keywords | |
def some_method(required_argument: nil, optional_argument: nil) | |
raise ArgumentError, 'wrong number of arguments (0 for 1..2)' if required_argument.nil? | |
p [required_argument, optional_argument] | |
end | |
some_method()# => ArgumentError: wrong number of arguments (0 for 1..2) | |
some_method(required_argument: 'bob')# => "['bob',nil]" | |
some_method('bob', 'dole')# => "['bob','dole']" | |
some_method(some_data)# => "['bob','dole']" | |
# 2.1.3 style using named keywords | |
def some_method(required_argument:, optional_argument: nil) | |
p [required_argument, optional_argument] | |
end | |
some_method()# => ArgumentError: missing keyword: required_argument | |
some_method(required_argument: 'bob')# => "['bob',nil]" | |
some_method('bob', 'dole')# => ArgumentError: missing keyword: required_argument | |
some_method(some_data)# => "['bob','dole']" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment