-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmethod_splat_arguments.rb
More file actions
40 lines (33 loc) · 1.01 KB
/
Copy pathmethod_splat_arguments.rb
File metadata and controls
40 lines (33 loc) · 1.01 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
# Splat arguments
# Splat arguments allow you to pass a variable number of arguments to a method. They are denoted by an asterisk (*) before the parameter name.
# When you use a splat argument, it collects all the remaining arguments into an array.
def greet(*names)
names.each do |name|
puts "Hello, #{name}!"
end
end
greet("Luthfi", "Skha", "Fikha", "Javier")
# Output:
# Hello, Luthfi!
# Hello, Skha!
# Hello, Fikha!
# Hello, Javier!
def sum(*numbers)
total = numbers.reduce(0) { |acc, num| acc + num }
puts "The sum of the numbers is #{total}."
end
sum(1, 2, 3, 4, 5)
# Output: The sum of the numbers is 15.
# If you want to pass an array of arguments to a method that accepts splat arguments, you can use the splat operator to expand the array into individual arguments.
numbers = [10, 20, 30, 40, 50]
sum(*numbers)
# Output: The sum of the numbers is 105.
members = Array.new(3)
members[0] = "Rina"
members[1] = "Akbar"
members[2] = "Fikha"
greet(*members)
# Output:
# Hello, Rina!
# Hello, Akbar!
# Hello, Fikha!