[英]Ruby: Parsing time from a string
我试图传递一个保存为字符串的时间数组( ["08:00:00", "18:00:00"]
),并通过辅助方法以更易读的方式返回它们。
但是,我不断收到辅助方法中的参数错误。 这对我来说很奇怪,因为如果我删除Time.parse(time_slot)
并简单地尝试使用time_slot.strftime("%I:%M %p")
转换时间,它会抛出一个错误undefined method `strftime' for "08:00:00":String
。 object 显然被传入 - 我不明白什么吗?
第 4 行:小时 << Time.parse(time_slot).strftime("%I:%M %p")
“”中没有时间信息
代码:
1: - I18n.t('date.day_names').each do |day|
2: - %w[starts ends].each_with_object([]) do |time_type, to_return|
3: - @hours = to_return << @facility.access_hours["#{time_type}_#{day.downcase}"]
4: - @hours.compact.tap do |hours|
5: = day
6: = hours
7: = time_helper(hours)
8: = byebug
(byebug) hours = ["08:00:00", "18:00:00"]
(byebug) time_helper(hours) = "08:00 AM - 06:00 PM"
辅助方法
def time_helper(time)
hours = []
time.each do |time_slot|
hours << Time.parse(time_slot).strftime("%I:%M %p")
end
hours.join(' - ')
end
这对我来说很奇怪,因为如果我删除 Time.parse(time_slot) 并简单地尝试使用 time_slot.strftime("%I:%M %p") 转换时间,它会抛出一个错误 undefined method `strftime' for “08:00:00”:字符串。 object 显然被传入 - 我不明白什么吗?
time_helper
正在使用类似["08:00:00", "", "18:00:00"]
的数组调用。
"08:00:00"
被解析,但是Time.parse
阻塞了""
。 如果您在"08:00:00"
上尝试time_slot.strftime("%I:%M %p")
strftime
错误,因为它是字符串,而不是时间。
您可以按照 PGiII 的建议通过使用@hours.reject(&:blank?)
来解决此问题,这将删除nil
和空字符串。 尽管您可能仍想弄清楚为什么@facility.access_hours
中有空白。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.