开发者

Adding things inside while loop causes syntax error

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜