ruby - Ruby嵌套使用变量有错误未定义方法`[]'
问题描述
我正在尝试创建一些东西来从电子邮件中提取我的日程安排并将其设置为自动添加到 Google 日历中。我正在尝试逐步获得它,因为我也在学习 Ruby,所以我不是在寻找完整的解决方案,只是帮助解决这个错误。据我所知,分配(或至少调用项目)应该在循环中运行。
我已经从我用来尝试查看是否是我的错误的所有打印中清理了代码,但是我使用的变量完全符合我在循环内的期望,而嵌套数组调用给出了我在循环之外的期望循环也是如此。使用直接名称 (schedule["Mon"]["Lunch"]) 给出了我期望的结果,但 schedule[currDay]["Lunch"] 没有。
str = "Monday, July 22, 2019 (GMT-05:00) Eastern Time (US & Canada)
Lunch_101306 10:30 AM 11:00 AM
Ready - Onsite_101306 11:00 AM 12:20 PM"
arr = str.split(/\n/)
schedule = {}
currDay = ''
arr.each {|x|
#if it matches day of week, set as current day, and create hash entry in schedule
if x.match?(/(?:Mon|Tues|Wed|Thurs|Fri|Sat|Sun)/) then
currDay = x.scan(/(Mon|Tues|Wed|Thurs|Fri|Sat|Sun)/)
schedule[currDay[0][0]] = {"Start" => 'Default', "Lunch" => 'Default', "End" => 'Default'}
#else if the entry has lunch ready or break in it
elsif x.match?(/(?:Lunch|Ready|Break)/) then
#store information in temp for name of line, and groups for start and end time.
tempArg = x.scan(/(Lunch|Ready|Break).*?(\d{1,2}:\d{2}).*?(\d{1,2}:\d{2})/)
#if it's lunch, add this to schedule's current day entry for lunch
if tempArg[0][0] == "Lunch" then
puts schedule[currDay]["Lunch"]
#schedule[currDay]["Lunch"] = tempArg[0][1]
end
#check for ready / break
end
}
预计puts schedule[currDay]["Lunch"]
输出“默认”,尽管这部分的目标是从 tempArg 中分配第二组超过该值。相反,我得到了错误
Traceback (most recent call last):
2: from C:/Users/User/Documents/Testing/test.rb:17:in `<main>'
1: from C:/Users/User/Documents/Testing/test.rb:17:in `each'
C:/Users/User/Documents/Testing/test.rb:31:in `block in <main>': undefined method `[]' for nil:NilClass (NoMethodError)
``
解决方案
您忘记了currDay
stores[["Mon"]]
而不仅仅是"Mon"
,因此schedule[currDay]["Lunch"]
您不需要做schedule[currDay[0][0]]["Lunch"]
或更好地只是将其存储"Mon"
在内部currDay
,以免混淆自己:
currDay = x.scan(/(Mon|Tues|Wed|Thurs|Fri|Sat|Sun)/)[0][0]
推荐阅读
- c - 使用结构打印链接列表
- javascript - 当Java程序循环数以千计的数据时,如何显示最终用户可见的进度条?
- javascript - 如何循环遍历表格单元格并显示一些分心的结果
- python - 如何根据另一个列表中的元素修改一个列表中的元素?
- react-native - 相邻的视图
- javascript - 加载 style.css 时出现 error_404
- gmail - 通过 Chrome 和 Firefox 在 Gmail 中访问时,HTML 电子邮件的显示方式有所不同。我该如何防止这种情况?
- python - 在编写 csv 时拟合两个参数
- java - Intellij 在运行仪表板中运行多个应用程序时显示端口号
- avfoundation - 使 CIContext.render(CIImage, CVPixelBuffer) 与 AVAssetWriter 一起工作