-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmethod_keyword_arguments.rb
More file actions
44 lines (33 loc) · 2.04 KB
/
Copy pathmethod_keyword_arguments.rb
File metadata and controls
44 lines (33 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# keyword arguments
# Named keyword allow you to specify the names of the parameters when calling a method. This can make your code more readable and allows you to pass arguments in any order.
# When you define a method with named keyword arguments, you use the syntax `parameter_name: default_value` in the method definition. When calling the method, you can specify the arguments using their names.
# REMEMBER keyword arguments must be put in the last position of the parameter.
def introduce(name:, age:, city:)
puts "My name is #{name}, I am #{age} years old, and I live in #{city}."
end
introduce(name: "Luthfi", age: 25, city: "Jakarta")
# Output: My name is Luthfi, I am 25 years old, and I live in Jakarta.
# We can add default values to named arguments. If an argument is not provided when calling the method, the default value will be used.
def introduce(name:, age: 23, city: "Unknown")
puts "My name is #{name}, I am #{age} years old, and I live in #{city}."
end
introduce(name: "Skha", city: "Bogor")
# Output: My name is Skha, I am 23 years old, and I live in Bogor.
# Named arguments can also be used in combination with splat arguments. This allows you to have a flexible number of arguments while still maintaining readability.
def introduce(*hobbies, name:, age:, city:)
puts "My name is #{name}, I am #{age} years old, and I live in #{city}."
unless hobbies.empty?
puts "My hobbies are: #{hobbies.join(', ')}."
end
end
introduce("Reading", "Traveling", name: "Fikha", age: 30, city: "Surabaya")
# Output:
# My name is Fikha, I am 30 years old, and I live in Surabaya.
# My hobbies are: Reading, Traveling.
# If you want to pass a hash of arguments to a method that accepts named keyword arguments, you can use the double splat operator (**) to expand the hash into individual keyword arguments.
def introduce(name:, age:, city:)
puts "My name is #{name}, I am #{age} years old, and I live in #{city}."
end
args = { name: "Fikha", age: 30, city: "Surabaya" }
introduce(**args)
# Output: My name is Fikha, I am 30 years old, and I live in Surabaya.