-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_optional_arguments.rb
executable file
·62 lines (47 loc) · 1.32 KB
/
test_optional_arguments.rb
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# Practice methods w/ optional arguments
def do_some_matherings(x, y, *z)
@x = x
@y = y
@z = z[0]
if @y != nil
puts "For x and y:"
puts " #{@x + @y}"
puts " #{@x * @y}"
else
puts "For x and z:"
puts " #{@x + @z}"
puts " #{@x * @z}"
end
end
do_some_matherings(5, 5)
puts
do_some_matherings(5, nil, 0)
# *z is not really 0, but an array: [0]
puts
def more_math(operator, start, *optional_args)
@total = start
if optional_args == []
else
if operator == "add"
optional_args.each do |i|
@total += i
end
elsif operator == "multiply"
optional_args.each do |i|
@total *= i
end
end
end
return @total
end
# since optional arguments become arrays, numerous arguments beyond the x'th (where x is the optional argument)
# are all a part of the option argument array
puts more_math("add", 10) # program does nothing with no optional arguments
puts more_math("multiply", 10) # program does nothing with no optional arguments
puts more_math("add", 0, 5) # optional_args == [5]
puts more_math("add", 0, 5, 10) # optional_args == [5, 10]
puts more_math("add", 0, 5, 10, 15) # optional_args == [5, 10, 15]
puts more_math("multiply", 1, 5) # optional_args == [5]
puts more_math("multiply", 1, 5, 10) # optional_args == [5, 10]
puts more_math("multiply", 1, 5, 10, 15) # optional_args == [5, 10, 15]
puts