Skip to content
syntax error, unexpected ...

syntax error, unexpected ...

DodaTech 3 min read

Ruby’s syntax error, unexpected means the parser hit a token it didn’t expect at that position — missing end, unmatched do/end, or a structural mistake.

What It Means

Ruby reads your source file character by character, grouping tokens into expressions. When the parser hits a keyword or symbol that doesn’t fit the current context — like seeing end when no block is open, or seeing ) without a matching ( — it raises a syntax error. The error includes the unexpected token and a line number, though the actual mistake may be earlier in the file.

Why It Happens

  • Missing end keyword for a def, class, module, if, or do block.
  • Unmatched parentheses, brackets, or braces.
  • Using the wrong operator (= instead of == in conditionals).
  • Forgetting commas in hash literals or method arguments.
  • Using a reserved keyword as a variable name.
  • Incorrect heredoc syntax or string interpolation.
  • Mixing tabs and spaces for indentation.

How to Fix It

Step 1: Count your end keywords

Every def, class, module, if, unless, case, begin, and do needs a matching end:

class Calculator
  def add(a, b)
    a + b
  end  # One end for def
       # One end for class

Step 2: Check do/end blocks

do needs end (unless you use { } for single-line blocks):

# Bad — missing end
[1, 2, 3].each do |n|
  puts n

# Good
[1, 2, 3].each do |n|
  puts n
end

Step 3: Validate parentheses and brackets

Make sure every opening (, {, [ has a matching closing ), }, ]:

result = calculate(a, b  # Missing closing )

Step 4: Check commas in hashes and arrays

# Bad — missing comma
fruits = ["apple" "banana", "cherry"]

# Good
fruits = ["apple", "banana", "cherry"]

# Bad hash
person = {name: "Alice" age: 30}

# Good
person = {name: "Alice", age: 30}

Step 5: Use = vs == correctly in conditionals

# Bad — assignment instead of comparison
if x = 10
  puts "ten"
end

# Good
if x == 10
  puts "ten"
end

Step 6: Use a linter to catch syntax errors

# Install and run RuboCop
gem install rubocop
rubocop your_file.rb

# Or use Ruby's built-in syntax check
ruby -c your_file.rb
Why does the syntax error point to the right line but the fix is earlier?
Ruby parses left-to-right and top-to-bottom. When it hits something unexpected, it reports the current position — but the real mistake (like a missing end) may be 10 lines above. The parser can’t know what you intended, so it reports where it got confused. Always check the lines above the reported line number.
What is the most common syntax error in Ruby?
Missing end keywords. Ruby uses explicit end to close blocks, methods, classes, and conditionals — unlike Python’s indentation-based blocks or JavaScript’s braces. Beginners often forget that def, class, if, and do each need their own end. Run ruby -c file.rb to check syntax without executing the file.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro