<- While loops
About this chapter ->

Writing good programs

Comments

A comment is any piece of text that starts with the # symbol. These are ignored by Ruby, so you can use it to write comments for yourself. For example:


#!/usr/bin/ruby

# Find the largest power of 2 
# less than 10_000
number = 1
while number < 10_000
    number *= 2
end
                       

Notice how the comment is simply a note that you make to yourself. Simply to help you remember what your code does.

How to use comments:



Indentation

Always indent your code. This is one of the most fundamental parts of good programming.

If you don't, your code will be illegible and you'll never manage to write anything but the simplest programs.

Good     Bad

# Add odd numbers
num, sum = 1, 0
while num < 100
    # % is remainder
    if num % 2 == 1
        sum += num
    end
    puts sum
end
                       

# Add odd numbers
num, sum = 1, 0
while num < 100
# % is remainder
if num % 2 == 1
sum += num
end
puts sum
end
                       

There are two identation standards. Either 4 spaces or 8 spaces. I like 4 spaces, but it's up to you.

<- While loops
About this chapter ->