Ruby 中的哈希与数组(我使用它们正确吗?)

发布于 2024-12-01 17:35:54 字数 195 浏览 0 评论 0原文

我本质上是在制作日历。每天要么被视为上班日,要么被视为休息日。不可能两者兼而有之。我接受用户输入并使用基本测试条件生成未来 365 天的日历。

我相信我应该使用日期作为键来使用哈希。我读到,只要我使用 ruby​​ 1.9,哈希值就会保持有序,如果我愿意的话,我可以像数组一样迭代它们。我相信当我显示日历时我会遍历它们。

这是正确的思考方式吗?

I am essentially building a calendar. Each day is either considered an on day or an off day. It can't be both. I take the users input and generate a calendar for the next 365 days out using what is basically a test condition.

I believe I should use a hash for this using the date as a key. I read that as long as I use ruby 1.9 the hashes stay in order and I can iterate through them like an array if I so choose. I believe I will iterate through them when I display the calendar.

Is this the correct way of thinking about it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

落墨 2024-12-08 17:35:54

Ruby 有一个集合类,您可以用它来存储“于”日期。由于集合内部是作为散列实现的,因此查找速度很快。示例(或多或少是一个稍微整理过的 IRB 会话):

require 'set' 
require 'date'

on_days = Set.new
on_days << Date.today + 1
on_days << Date.today + 7

def on_day?(on_days, date_to_check)
  on_days.include? date_to_check
end 
>> on_day?(on_days, Date.today) #=> false
>> on_day?(on_days, Date.today+1) #=> true

在真实的程序中,您可能会将其包装在一个类中,并使用 on_days 作为实例变量而不是传递它,但原理应该是一样的。

Ruby has a set class, which you could use to store "on" dates. Since sets internally are implemented as hashes, lookups are fast. Example (more or less a slighly tidied up IRB session):

require 'set' 
require 'date'

on_days = Set.new
on_days << Date.today + 1
on_days << Date.today + 7

def on_day?(on_days, date_to_check)
  on_days.include? date_to_check
end 
>> on_day?(on_days, Date.today) #=> false
>> on_day?(on_days, Date.today+1) #=> true

In a real program you'd probably wrap this up in a class, with on_days as an instance variable instead of passing it around, but the principle should be the same.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文