0

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
  end
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

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! it's pretty confusing, the kEND error made me think that there's a problem with mismatched 'end's
1

Besides, there is a bracket missing in your regexp (character class).

/0-9]{1,4}/

It should read

/[0-9]{1,4}/

Comments

0

There is no C-style increment/decrement operator. Instead use

invalid = invalid + 1

or

invalid += 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.