Unexpected keyword_end error, yet syntax seems fine

若如初见. 提交于 2019-11-26 11:42:33

问题


This function is supposed to pull names from a Comma Separated Values file, and place them into an array.

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

I\'m getting the following error:

syntax error, unexpected keyword_end

I would be as happy to be referred to an existing question that solves my problem as to have someone answer me directly.


回答1:


Your error comes from line:

current_word ++

There's no such syntax in Ruby. It should be:

current_word += 1

What's more, you create your regexp incorrectly. It should be:

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

There may be some other errors that I didn't notice.




回答2:


On this line:

current_word ++

You are telling Ruby to add something to current_word, but you never tell it what to add, instead there's an end directly on the next line. You are missing the operand to the unary +. It should be something like

current_word + something_else

or

current_word + +something_else

In Ruby, whitespace is allowed around operators, so

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

and even

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

is perfectly fine, so if you combine the two, you get that

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

is also perfectly fine, and since whitespace around operands is perfectly fine but optional,

a+b

and

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

is also perfectly fine.

That's why you only get the error on the next line with the end, because only there can Ruby tell that you are missing the operand to the unary prefix + operator.



来源:https://stackoverflow.com/questions/24950578/unexpected-keyword-end-error-yet-syntax-seems-fine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!