While I love what ray does for these exercises, I often feel like there is not much challenge left in doing them in CF. However I am nowhere near as good at Ruby as I am at CF so I thought I would do a version of his code challenge in Ruby.
So the first 11 lines of the app do the code prep that he gave on his blog. This sets up the data to loop over to create the song. Then I have 8 lines of code that actually do all the output for the song. 4 of which are actual code stuff. and it could be less but I wanted to make sure that on any but the first verse we sing “and a partridge…”.
So without further ado here is my solution for Ray’s code challenge
class Gift
attr_accessor :id, :name
def initialize (id, name)
@id = id
@name = name
end
end
gifts = Array.new()
giftNames = ["A partridge in a pear tree","Two turtle doves","Three French hens","Four calling birds","Five golden rings","Six geese a-laying", "Seven swans a-swimming","Eight maids a-milking","Nine ladies dancing","Ten lords a-leaping","Eleven pipers piping","Twelve drummers drumming"]
giftNames.each_index { |i| gifts.push Gift.new(i,giftNames[i]) }
#Actual output code for song
gifts.each do |g|
puts "On the #{g.id+1} day of christmas, my true love gave to me:"
g.id.downto 0 do |gi|
verse = "#{gifts[gi].name}"
verse = "and " + verse if (g.id != 0 and gi == 0)
puts "\t" + verse
end
end
If you are on a mac running this code is very simple. Copy it into a file called Ray.rb, save the file to your computer, then run `ruby Ray.rb` (get the path right). You will see the song output. If you are on a pc you have to actually have ruby installed, but I am not gonna tell you how.