Skip to content

Instantly share code, notes, and snippets.

@KazW
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KazW/609573f0062617e2c249 to your computer and use it in GitHub Desktop.
Save KazW/609573f0062617e2c249 to your computer and use it in GitHub Desktop.
2.1.3 method declaration syntax
# 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