Ruby 中的哈希与数组(我使用它们正确吗?)
我本质上是在制作日历。每天要么被视为上班日,要么被视为休息日。不可能两者兼而有之。我接受用户输入并使用基本测试条件生成未来 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Ruby 有一个集合类,您可以用它来存储“于”日期。由于集合内部是作为散列实现的,因此查找速度很快。示例(或多或少是一个稍微整理过的 IRB 会话):
在真实的程序中,您可能会将其包装在一个类中,并使用
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):
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.