syntax error, unexpected ...
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
endkeyword for adef,class,module,if, ordoblock. - 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 classStep 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
endStep 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"
endStep 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.rbBuilt by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro