Geo
Geo

Reputation: 96897

How to make Ruby's N ends look better?

As I write some scripts, I usually reach a point where my code looks like this :

          end
        end
      end
    end
  end
end

I don't know about you, but this look very ugly to me. Can something be done about this?

Upvotes: 2

Views: 315

Answers (6)

Andrew Grimm
Andrew Grimm

Reputation: 81570

If you're happy to compile your own Ruby, you could use ennnnnnnd style syntax (link is to RubyKaigi talk). Unfortunately for you, this has been suggested and rejected by Ruby core.

Upvotes: 1

Gene T
Gene T

Reputation: 5176

I have seen nested "{ }" blocks and 4-space soft tabs and:

end;end;end;end

I suppose this saves vertical space, but I don't recommend, The above comments on avoiding deep nesting and commenting your block-ending lines are the valid approaches. Maybe deep nesting is to avoid method call overhead for things that need speeding up, but readability almost always trumps that kind of "optimization"

Upvotes: 1

auser
auser

Reputation: 14378

Try to use small, testable functions. Not only are your functions and more importantly logic easy to test, but your code becomes way more readable.

Upvotes: 2

Ethan
Ethan

Reputation: 60169

The advice to break up into smaller pieces is good. But if you need a lot of nested blocks like that, you can label the end keywords with comments.

    end # End conditional statement
  end # End method declaration
end # End class declaration

Still ugly, but at least clearer.

The other options previously mentioned are preferable.

Upvotes: 5

Barry Kelly
Barry Kelly

Reputation: 42152

Don't nest your code so much? Refactor to use more methods? Use blocks passed to other routines instead?

Generally speaking, deep nesting is an indicator that a method is getting too complex and should be broken up. It can help for implicit structural documentation too, by naming the inner compound statements according to their refactored methods.

Upvotes: 18

Andrew Y
Andrew Y

Reputation: 5107

If those inner blocks do something easy to name (and maybe reusable?), why not refactor them into small separate functions ? Then you'd end up with much shorter sequences of end's.

Otherwise another approach is using Python :-)

Upvotes: 4

Related Questions