There are 3 basic types of comments in Ruby. Single line, Block, and Inline. Single line and Inline are the most common, but you'll occasionally see large Block comments if the programmer needs to explain something in great detail. Comments are generally used to provide more context for your code or to prevent problematic or incomplete code from executing while you debug it.
Comments in Ruby typically begin with a hash mark #
, like this:
Single Line Comments
# Here is a comment
Here are a few examples of how you could use comments in your code.
# Displays a message to the user
puts "Hello World"
# Sets a variable to an array
array = ['fish', 'dog', 'cat']
This usage isn't very practical because anyone with a basic understanding of Ruby already knows what those two lines of code do. It's better to write your comments when further explanation is needed for complex lines.
Block Comments
Here, each line begins with a hash mark #
. Block comments are good for when you need to explain somthing in more depth than one line. This can be great for complex problems, but should be avoided if it becomes redundant.
# This Ruby method takes in two numbers as arguments, a and b, and then
# adds them together. If I were to run the method like add_two_numbers(4, 5)
# my return value would be 9. That is how the code
# would run.
def add_two_numbers(a, b)
a + b
end
I am obviously being facetious here and this isn't a great example of a use case, but I think my point of not being redundant gets across.
There is also another way to use Block Comments, but it is hardly ever used. This way invloves using =begin
and =end
at the boundaries of your multi-line comment. Here's an example:
=begin
This is a multi-line comment.
This enables you to not to have to write multiple hash marks and still
span multiple lines.
=end
The =begin
and =end
must be at the beginning of their respective lines. They can't be indented. It's for this reason they are rarely used.
Inline Comments
Inline comments occur on the same line as your code and follow the code itself. They also begin with a hash mark #
like most of the previous examples.
[code] # Inline comment about the code
The usage for these follow the same principles as single line code. If more explanation is necessary, feel free to use them but don't over explain and be redundant (says the guy who has used that word 3 times in this blog post).
Conclusion
To sum it all up, comments are a great way to increase the readability of your code. This comes at a price if you start throwing comments every where. Just use them where needed and try not to over explain yourself. With that in mind, comments can be a great asset to your fellow programmers and even your future self!