我用case语句查看时间。怎么办?
答案 0 :(得分:3)
使用范围:
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
范围适用于各种值。您也可以使用Date
:
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
更新:Ruby 1.9破坏了时间范围,因此该示例仅适用于Ruby 1.8.7。 Date示例适用于两个版本。在1.9中,您可以使用此代码来匹配时间:
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
答案 1 :(得分:0)
只需使用顶部没有定义变量的版本......
t = event.time # arbitrary example.
case
when t <= Time.now
# Event is in the past.
else
# Event is in the future.
end