2012-07-29 46 views
1

我有以下助手即應把一天的話取決於數量:如何在Rails中增加一天助手?

def day_in_words(number) 
    case number 
    when 0 
     "Sunday" 
    when 1 
     "Monday" 
    when 2 
     "Tuesday" 
    when 3 
     "Wednesday" 
    when 4 
     "Thursday" 
    when 5 
     "Friday" 
    when 6 
     "Saturday" 
    when 7 
     "Sunday" 
    when 8 
     "Monday" 
    when 9 
     "Tuesday" 
    when 10 
     "Wednesday" 
    when 11 
     "Thursday" 
    ... 
    when 16 
     "Sunday" 
    when 17 
     "Monday" 
    when 18 
     "Tuesday" 
    when 19 
     "Wednesday" 
    when 20 
     "Thursday" 
    when 21 
     "Friday" 
    else 
     "Unknown Day" 
    end 
    end 

如何重構該助手?

想到的

回答

7

您是否嘗試過這種可能 - >

Date::DAYNAMES[number%7] 
+0

我知道那裏肯定已經有內置的數組了...... – 2012-07-29 17:08:19

0

第一件事就是使用模7作爲指標來天的名稱的數組:

def day_in_words(number) 
    return ['Sun','Mon','Tue','Wed','Thurs','Fri','Sat'][number % 7] 
end 
1

你可以使用:

def day_in_words(number) 
    return "Unknown Day" if number > 20 
    %w[sun mon tue wed thu fri sat].cycle(3).to_a[number] 
end