Skip to content

Instantly share code, notes, and snippets.

@KazW

KazW/example.rb

Last active Aug 29, 2015
Embed
What would you like to do?
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