首页 > 解决方案 > 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)
``

标签: rubyhashmap

解决方案


您忘记了currDaystores[["Mon"]]而不仅仅是"Mon",因此schedule[currDay]["Lunch"]您不需要做schedule[currDay[0][0]]["Lunch"]或更好地只是将其存储"Mon"在内部currDay,以免混淆自己:

currDay = x.scan(/(Mon|Tues|Wed|Thurs|Fri|Sat|Sun)/)[0][0]

推荐阅读