开发者

Max and min time checks in case statement using Ruby?

开发者 https://www.devze.com 2023-02-03 23:48 出处:网络
I what to check a time wit开发者_Python百科h a case statement. How to do?Use ranges: case time when (Time.now - 60)..(Time.now) then puts \'within the last minute\'

I what to check a time wit开发者_Python百科h a case statement. How to do?


Use ranges:

case time
when (Time.now - 60)..(Time.now) then puts 'within the last minute'
when (Time.now - 3600)..(Time.now) then puts 'within the last hour'
end

Ranges work with all sorts of values. You can use Dates too:

case date
when (Date.today - 1)..(Date.today) then puts 'less than a day ago'
when (Date.today - 30)..(Date.today) then puts 'less than a month ago'
end

Update: Ruby 1.9 broke Time ranges, so that example works only in Ruby 1.8.7. The Date example works in both versions though. In 1.9 you can use this code to match a Time:

case time.to_i
when ((Time.now - 60).to_i)..(Time.now.to_i) then puts 'within the last minute'
when ((Time.now - 3600).to_i)..(Time.now.to_i) then puts 'within the last hour'
end


Just use the version that doesn't have a defined variable at the top...

t = event.time  # arbitrary example.

case
when t <= Time.now
  # Event is in the past.
else
  # Event is in the future.
end
0

精彩评论

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