开发者

Ruby: day selection program (select next available day from a list)

I'm tryind to build a helper to select the next available day from a list.

I have a list of days as a reference (those are the day where I want something to happen)

class_list = ["Monday","Saturday","Sunday"]

I need to check the current day and match it in the list. If it's part of the list I select it, if it isn't I select the next one from the list.

this is what i have so far:

#select current day, get its name value and weekday number value
today = Time.now
today_name = today.strftime("%A")
#not sure which of the 2 following line is better
#today_index = Date开发者_如何学编程Time.parse(today_name).wday 
today_index = today.strftime("%u").to_i

Then I do the matching

if class_list.include? today_name
  #victory!!!
  puts today_name
else
  puts "find next day"
  class_list.each do |x|
    if DateTime.parse(x).wday > today_index
      puts "result #{x}"
      break
    end
  end
end 

When I run it seems to work fine, but as i'm just learning Ruby i'm always wondering if i'm not overcomplicating things.

Does this code looks alright to you Ruby masters?


require 'date'

def next_date_from(ar)
  cur_day = Date.today
  cur_day += 1 until ar.include?(cur_day.strftime('%A'))
  cur_day
end

puts next_date_from(%w(Monday Saturday Sunday))
#=>2011-10-01


I would better have a map linking a given day to the following one and a default value if the day is not found:

days = {:Monday => :Tuesday, :Tuesday => :Wednesday ...}
days.default = :Monday

When you do days[:Monday] you get :Tuesday when you try to get a non existing entry, you get the default.


For the part:

if class_list.include? today_name
  #victory!!!
  puts today_name
else
  puts "find next day"
  class_list.each do |x|
    if DateTime.parse(x).wday > today_index
      puts "result #{x}"
      break
    end
  end
end 

You could write it like this:

if class_list.include? today_name
  #victory!!!
  puts today_name
else
  puts "find next day"
  result = class_list.find {|e| DateTime.parse(e).wday > today_index }
  puts "result = #{result}"
end 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜