ruby - 如何返回带有 case 语句的散列?

标签 ruby hashmap

我正在尝试编写一个函数来获取日期的天数,例如,今天(3 月 29 日)是一年中的第 88 天。然后它返回一个包含月份和月份中的日期的散列:

{"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

最佳答案

你需要使用裸case如果你想在每个 when 中使用表达式条款。否则,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

关于ruby - 如何返回带有 case 语句的散列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15709645/

相关文章:

java - Spring 形式的 Hashmap

java - 将 HashMap 绑定(bind)到 ComboBox

java - 如何在 Java 中对 HashMap 进行排序

ruby-on-rails - 有人可以向我解释 class << self 吗?

ruby-on-rails - Ruby 中有哪些工具或实践可以用于服务器中的海量实时数据及其在浏览器上的可视化?

ruby - irb 不加载我创建的 gem

javascript - JavaScript 中的删除运算符如何工作?

java - 当 HashMap 的初始容量不是 2 的幂时指定它是否比根本不指定更好?

ruby - 正则表达式数组(["number", "number",...])

ruby-on-rails - 使用 Rails API 进行设计 - current_user