开发者

Hashes vs Arrays In Ruby (Am I using them right?)

I am essentially building a calendar. Each day is either considered an on day or an of开发者_运维百科f 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜