blob: 24a2aab3c35e721e698c2338371f519cfd5567d6 (
plain)
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
|
require 'getoptlong'
options = GetoptLong.new(
['--number', '-n', GetoptLong::REQUIRED_ARGUMENT],
['--verbose', '-v', GetoptLong::OPTIONAL_ARGUMENT],
['--help', '-h', GetoptLong::NO_ARGUMENT]
)
def help(status = 0)
puts <<~HELP
Usage:
-n n, --number n:
Compute Fibonacci number for n.
-v [boolean], --verbose [boolean]:
Show intermediate results; default is 'false'.
-h, --help:
Show this help.
HELP
exit(status)
end
def print_fibonacci (number)
return 0 if number == 0
return 1 if number == 1 or number == 2
i = 0
j = 1
(2..number).each do
k = i + j
i = j
j = k
puts j if @verbose
end
puts j unless @verbose
end
options.each do |option, argument|
case option
when '--number'
@number = argument.to_i
when '--verbose'
@verbose = if argument.empty?
true
elsif argument.match(/true/i)
true
elsif argument.match(/false/i)
false
else
puts '--verbose argument must be true or false'
help(255)
end
when '--help'
help
end
end
unless @number
puts 'Option --number is required.'
help(255)
end
print_fibonacci(@number)
|