a

Ruby code posted
created at 02 Jul 21:21

Edit | Back
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
class Bottles
  def song
    verses(99, 0)
  end
  def verses(starting, ending)
    starting.downto(ending).collect {|i| verse(i)}.join("\n")
  end
  def verse(number)
    bottle_number = BottleNumber.for(number)
    "#{bottle_number} of milk on the wall, ".capitalize +
    "#{bottle_number} of milk.\n" +
    "#{bottle_number.action}, " +
    "#{bottle_number.successor} of milk on the wall.\n"
  end
end

class BottleNumber
  def self.for(number)
    case number
    when 0
      BottleNumber0
    when 1
      BottleNumber1
    when 6
      BottleNumber6
    else
    begin
      const_get("BottleNumber#{number}")
    rescue NameError
      BottleNumber
    end.new(number)
  end
  attr_reader :number
  def initialize(number)
    @number = number
  end
  def to_s
    "#{quantity} #{container}"
  end
  def container
    "bottles"
  end
  def quantity
    number.to_s
  end
  def action
    "Take #{pronoun} down and pass it around"
  end
  def pronoun
    "one"
  end
  def successor
    BottleNumber.for(number - 1)
  end
end
class BottleNumber0 < BottleNumber
  def quantity
    "no more"
  end
  def action
    "Go to the store and buy some more"
  end
  def successor
    BottleNumber.for(99)
  end
end
class BottleNumber1 < BottleNumber
  def container
    "bottle"
  end
  def pronoun
    "it"
  end
end
class BottleNumber6 < BottleNumber
  def quantity
    "1"
  end
  def container
    "six-pack"
  end
end
1.47 KB in 4 ms with coderay