Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return a hash with a case statement?

Tags:

hashmap

ruby

I am trying to write a function that takes the day number of the date, for example, today (March 29) is the 88th day of the year. It then returns a hash containing the month, and the day in the month:

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

I can't quite figure out what is wrong with this code, but it always returns nil. Any thoughts? I am using 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
like image 751
Matt Adelman Avatar asked Feb 13 '26 00:02

Matt Adelman


1 Answers

You need to use a bare case statement if you want to use an expression inside each when clause. Otherwise, Ruby will call (days <= 31) === days, which will never be true.

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

This implementation however ignores leap days and it seems simpler and more correct to just do this:

def number_to_date(days)
  date = Date.ordinal(Date.today.year, days)
  {"month" => Date::MONTHNAMES[date.month], "day" => date.day}
end
like image 172
Rein Henrichs Avatar answered Feb 15 '26 17:02

Rein Henrichs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!