Live number in ruby
Live number is a number of the total sum for birthday year,months and days.
Below is the ruby implementation:
def live_number(birthday) reduce("#{birthday.year}#{birthday.month}#{birthday.day}") end def reduce(sum) add_sum = each_digits(sum).reduce(:+) add_sum >= 10 ? reduce(add_sum) : add_sum end def each_digits(num) num.to_s.split("").map{|c| c.to_i } end
spec:
describe "live_number" do before :each do @birthdays = [Time.new(2001,3,5), Time.new(1978,5,26), Time.new(1962,10,1)] @birth = {:day => Time.new(1981,6,11), :ans => 9 } end it "return number of live by birthday" do @birthdays.each do |day| live_number(day).should be_a_kind_of(Fixnum) end end it "return the correct number of live" do @birthdays.each do |day| live_number(day).should == 2 end end it "return correct number with specific birthday" do live_number(@birth[:day]).should == @birth[:ans] end end