2013-03-29 42 views
3

我想寫一個函數,需要日期的日期,例如,今天(3月29日)是一年中的第88天。然後,它返回一個包含一個月的哈希,和白天在一個月:如何使用case語句返回散列?

{"month" => "March, "day" => 29} 

我不能完全弄清楚什麼是錯這個代碼,但它總是返回nil。有什麼想法嗎?我正在使用Ruby 1.8.7 p358。

def number_to_date(days) 
    date = case days 
    when days <= 31 then {"month" => "January", "day" => days} 
    when days <= 59 then {"month" => "February", "day" => (days - 31)} 
    when days <= 90 then {"month" => "March",  "day" => (days - 59)} 
    when days <= 120 then {"month" => "April",  "day" => (days - 90)} 
    when days <= 151 then {"month" => "May",  "day" => (days - 120)} 
    when days <= 181 then {"month" => "June",  "day" => (days - 151)} 
    when days <= 212 then {"month" => "July",  "day" => (days - 181)} 
    when days <= 243 then {"month" => "August", "day" => (days - 212)} 
    when days <= 273 then {"month" => "September", "day" => (days - 243)} 
    when days <= 304 then {"month" => "October", "day" => (days - 273)} 
    when days <= 334 then {"month" => "November", "day" => (days - 304)} 
    when days <= 365 then {"month" => "December", "day" => (days - 334)} 
    end 
    return date 
end 

回答

5

如果要使用每個when子句中的表達式,則需要使用純粹的case語句。否則,Ruby將會調用(days <= 31) === days,這永遠不會是真的。

def number_to_date(days) 
    date = case 
    when days <= 31 then {"month" => "January", "day" => days} 
    when days <= 59 then {"month" => "February", "day" => (days - 31)} 
    # ... 
    end 
    return date 
end 

然而,這實現忽略飛躍天,似乎更簡單,更正確的只是這樣做:

def number_to_date(days) 
    date = Date.ordinal(Date.today.year, days) 
    {"month" => Date::MONTHNAMES[date.month], "day" => date.day} 
end 
+0

賴的執行是好的,可以隨意忽略我的答案:) –

2

你只需要一個小小的語法調整。從date = case days聲明中刪除days。否則,您的條件語句將與days變量進行比較。