Alan H.
Alan H.

Reputation: 16588

Is there a quick way to find missing end’s in Ruby?

syntax error, unexpected $end, expecting keyword_end

We’ve all been there! Assuming enough code changed that a quick glance at git diff or the like doesn’t make it obvious, is there an easy way to find that missing end (short of switching to an indentation-based language like Python)?

FWIW, I use Sublime Text 2 as my editor.

Upvotes: 19

Views: 9061

Answers (3)

Lukas_Skywalker
Lukas_Skywalker

Reputation: 2070

Edit (2023): this is now part of Ruby 3.2 and doesn‘t need to be required separately!

————————————

Edit (2022): the gem is now called syntax_suggest and is part of the Ruby standard library!

————————————

Since December 2020, there is also the dead_end gem which helps you detect missing ends.

The easiest way to get started is to install the gem:

gem install dead_end

and run it directly from your console, providing the file name to scan:

dead_end myfile.rb

This will provide you with a more helpful error message:

  43          if (col_idx - 1) % 3 == 0
  50            if !contains?(doc, node)
❯ 51              doc.add_child(node)
❯ 52              tree.
  53            end
  54          end

See the documentation for more options.

Upvotes: 5

Sunwoo Yang
Sunwoo Yang

Reputation: 1243

If you're using rails, you can run the problematic file specifically with the -w flag.

If you still can't find the offending mismatch, then my go-to way of solving this problem is just commenting out chunks of code until I can isolate the problematic area.

On OS X you can use command + / to comment out the highlighted piece of text.

Upvotes: 2

sunnyrjuneja
sunnyrjuneja

Reputation: 6123

If you're using Ruby 1.9, try the -w flag when running your ruby program.

# t.rb
class Example
  def meth1
    if Time.now.hours > 12
      puts "Afternoon"
  end
  def meth2
    # ...
  end
end

ruby t.rb  
=> t.rb:10: syntax error, unexpected $end, expecting keyword_end

ruby -w t.rb
=> t.rb:5: warning: mismatched indentations at 'end' with 'if' at 3
   t.rb:9: warning: mismatched indentations at 'end' with 'def' at 2
   t.rb:10: syntax error, unexpected $end, expecting keyword_end

Source:

http://pragdave.blogs.pragprog.com/pragdave/2008/12/ruby-19-can-check-your-indentation.html

Upvotes: 39

Related Questions