Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

syntax

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.

like image 496
Alan H. Avatar asked Oct 12 '12 01:10

Alan H.


2 Answers

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

like image 164
sunnyrjuneja Avatar answered Nov 01 '22 16:11

sunnyrjuneja


Edit: 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.

like image 4
Lukas_Skywalker Avatar answered Nov 01 '22 17:11

Lukas_Skywalker