【问题标题】:Unexpected keyword_end error, yet syntax seems fine意外的keyword_end错误,但语法似乎很好
【发布时间】:2014-07-25 07:46:27
【问题描述】:

这个函数应该从逗号分隔值文件中提取名称,并将它们放入一个数组中。

def xprt_csv_to_ary(csv_file)
    namecatcher_regex = "/^[\.{1}]([A-Z]+)\.{3}/" # Matches up to char before next name
    current_word = 0
    names_array = []
    while current_word < 5000
        if current_word == 0
            name = csv_file.readline.match(namecatched_regex)
        else
            name = csv_file.past_match.match(namecatcher_regex)
        end
        names_array[current_word] = name
        current_word ++
    end
    return names_array
end

我收到以下错误:

syntax error, unexpected keyword_end

如果有人直接回答我的问题,我会很高兴被提及解决我的问题的现有问题。

【问题讨论】:

  • 标题和问题中的错误信息不匹配。它是哪一个?是否有缺少 end 或太多?

标签: ruby syntax-error


【解决方案1】:

您的错误来自以下行:

current_word ++

Ruby 中没有这样的语法。应该是:

current_word += 1

此外,您错误地创建了正则表达式。应该是:

namecatcher_regex = /^[\.{1}]([A-Z]+)\.{3}/

可能还有一些我没有注意到的其他错误。

【讨论】:

  • 非常感谢!我想我可以从这里拿走它。 :)
【解决方案2】:

在这一行:

current_word ++

你告诉 Ruby 向current_word 添加一些东西,但你从来没有告诉它什么要添加,而是直接在下一行有一个end。您缺少一元 + 的操作数。应该是这样的

current_word + something_else

current_word + +something_else

在 Ruby 中,运算符周围允许有空格,所以

a + 
b
# equivalent to a + b, which is equivalent to a.+(b)

甚至

+ 
a
# equivalent to +a, which is equivalent to a.+@()

非常好,所以如果你把两者结合起来,你就会得到那个

a + + 
b
# equivalent to a + +b, which is equivalent to a.+(b.+@())

也很好,因为操作数周围的空格很好但可选,

a+b

a ++ 
b
# equivalent to a + +b as above

也很好。

这就是为什么您只会在带有endnext 行中收到错误,因为只有在那里 Ruby 才能告诉您缺少一元前缀 + 运算符的操作数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 2015-09-09
    • 1970-01-01
    相关资源
    最近更新 更多