Inline comments in Ruby

I'd just like to add that rdoc — Ruby's built-in documentation builder — can utilize the comments within your code to build an initial set of documentation. From what I've understood in my recent reading, the "Ruby way" suggests that your code should be readable and self-explanatory, but that comments are a valuable and simple way to build documentation in early development, before sending a project off to a proper documentation team.

On the subject of inline comments, my use-case is that I find myself working on longish one-liners in irb before committing them to my properly formatted source files. Perhaps many people don't mind working with line-breaks in their development environment, but with my limited knowledge of the toolset at the moment, I'm finding it tedious to repeat previous commands. I'm nearly certain this is due to my failure to grok the tools at hand, be it irb, pry and what-have-you. At the moment, I'm wrapping any code which I desire to comment inline inside of a string object, which I must later remove or "uncomment" by removing the string wrapper.

Take it or leave it, but those are my two cents! Keep on Rubying on!

Addendum:

It pays to read the pry doc! A pry method is bound to every object, including the main. Calling it executes a sub-shell in the current prompt that allows you to analyze any object within the current scope. It is available in any context, including the main pry prompt. Coupled with the the amend-line, edit, hist, play commands in Pry, this sates my desire for inline comments, although I'm still unaware of any feature in pry which will load a previous command into the current prompt's input for editing.

Invoking the text editor tends to distract me a fair bit, not only because it removes the contents of the shell buffer from visibility on a single display (e.g. laptop), but especially since it removes all of the helpful pry tab completions and commands. I'd like to see pry, or another REPL which enables use of the cursor across multiple lines, since I'm still finding the need to use one-liners.


No, Ruby does not have inline comments.

Comments of this style have a tendency to reduce readability, since they makes the code harder to follow.

In your case it would be best to split your array items into separate rows and comment out the one row.

my_array = ['first',
#           'second',
            'third',
            'fourth']

Tags:

Ruby

Comments