Can someone tell me difference between theese two code examples? What changes when putting ":" at the end of variable name?
def initialize(email:)
@email = email
end
def initialize(email)
@email = email
end
CodePudding user response:
email:
in the method definition argument means that the method will be expecting a key-value pair as the method arguments.
Sample initialization call:
YourClass.new(email: email_param)
while a simple email
in the method definition argument means that the method will assign the passed argument to the variable email
.
Sample initialization call:
YourClass.new(email_param)
CodePudding user response:
email:
is keyword argument
Keyword arguments follow any positional arguments and are separated by commas like positional arguments. You must use Kwarg can use default value
It work this way:
def my_method(arg1:, arg2: "default", arg3:)
puts "arg1: #{arg1}, arg2: #{arg2}, arg3: #{arg3}"
end
my_method(arg3: 3, arg1: 1)
# will print arg1: 1, arg2: default, arg3: 3
my_method(arg2: 2, arg1: 1, arg3: 3)
# will print arg1: 1, arg2: 2, arg3: 3
my_method(arg2: 2)
# will raise ArgumentError (missing keywords: arg1, arg3)
Arguments order is important if these arguments are not keyword
def my_method(arg1, arg2 = "default", arg3)
puts "arg1: #{arg1}, arg2: #{arg2}, arg3: #{arg3}"
end
my_method(1, 3)
# will print arg1: 1, arg2: default, arg3: 3
my_method(1, 2, 3)
# will print arg1: 1, arg2: 2, arg3: 3
my_method(1)
# will raise ArgumentError (wrong number of arguments (given 1, expected 2..3))