-
Notifications
You must be signed in to change notification settings - Fork 353
Expand file tree
/
Copy path11_classes.rb
More file actions
61 lines (55 loc) · 1.88 KB
/
11_classes.rb
File metadata and controls
61 lines (55 loc) · 1.88 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# Write a program that outputs the lyrics for "Ninety-nine Bottles of Beer on the Wall"
# Your program should print the number of bottles in English, not as a number. For example:
#
# Ninety-nine bottles of beer on the wall,
# Ninety-nine bottles of beer,
# Take one down, pass it around,
# Ninety-eight bottles of beer on the wall.
# ...
# One bottle of beer on the wall,
# One bottle of beer,
# Take one down, pass it around,
# Zero bottles of beer on the wall.
#
# Your program should not use ninety-nine output statements!
# Design your program with a class named BeerSong whose initialize method
# receives a parameter indicating the number of bottles of beer initially on the wall.
# If the parameter is less than zero, set the number of bottles to zero. Similarly,
# if the parameter is greater than 99, set the number of beer bottles to 99
# Then make a public method called print_song that outputs all stanzas from the number of bottles of beer down to zero.
# Add any additional methods you find helpful.
class BeerSong
attr_accessor :beers
def initialize(beers)
beers = 0 if beers < 0
beers = 99 if beers > 99
self.beers = beers
end
def print_song
beers.downto 1 do |i|
print_stanza i
end
end
def print_stanza(n)
if n.zero?
String.new
else
puts "#{translate n} #{bottle n} of beer on the wall,"
"#{translate n} #{bottle n} of beer,"
"Take on down, pass it around,"
"#{translate n - 1} #{bottle n - 1} of beer on the wall."
end
end
def bottle(n)
if n == 1 then 'bottle' else 'bottles' end
end
def translate(n)
if 0 <= n && n <= 19
%w(zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fiftenn sixteen seventeen eighteen nineteen)
elseif n % 10 == 0
%w(zero ten twenty thirty forty fifty sixty seventy eigthy ninety)[n/10]
else
"#{translate n/10*10}-#{translate n%10}".downcase
end.capitalize
end
end