I'm trying to read and process lines from a file in Ruby.
I have a while loop that reads each line. If the all the while loop does is split the lines, it works fine. When I add a regex matching clause, I get a syntax error, unexpected kEND and syntax error, unexpected $end, expecting kEND
Specifically, here is the code which "compiles"
def validate
invalid = 0
f = File.open(ARGV[0], "r")
while (line = f.gets)
vals = line.split(",")
end
end
if (ARGV[1] == "validate")
validate
end
while this code
def validate
invalid = 0
f = File.open(ARGV[0], "r")
while (line = f.gets)
vals = line.split(",")
match0 = Regexp.new(/0-9]{1,4}/)
unless (match0.match(vals[0]))
invalid ++
end
e开发者_StackOverflow社区nd
end
if (ARGV[1] == "validate")
validate
end
throws the error
schedule.rb:10: syntax error, unexpected kEND
schedule.rb:18: syntax error, unexpected $end, expecting kEND
The syntax error is not due to the regex. It's due to the "++". Ruby doesn't have the "++" operator. Instead, you should use:
invalid += 1
Besides, there is a bracket missing in your regexp (character class).
/0-9]{1,4}/
It should read
/[0-9]{1,4}/
There is no C-style increment/decrement operator. Instead use
invalid = invalid + 1
or
invalid += 1
精彩评论