Information Technology Reference
In-Depth Information
It is important to document why you are writing code. Use comments to explain why you
chose to implement your code in the way you did and describe the alternative approaches
you considered. Jeff Atwood, of Stack Exchange and Discourse fame, brilliantly explains the
purpose of comments this way: “Code tells you how, comments tell you why.”
For example, consider the following Ruby code snippet, which buys bacon if there are cur-
rently fewer than five strips. By reading the code you can understand what the code does, but
it is not clear why the code was written in the first place:
iif bacon . strips < 5
buy_bacon
end
end
The following code adds a simple comment explaining why we should buy more bacon when
there are fewer than five strips. It is helpful to understand the context around this bacon pur-
chase: Jake likes to eat five pieces of bacon in the morning, so we want to have enough ba-
con on hand at all times:
# Jake eats 5 pieces of bacon each morning
iif bacon . strips < 5
buy_bacon
end
end
Variables
As we just saw in the preceding example, variables in Ruby are assigned from left to right:
variable = 2 # This assigns the value 2 to variable.
Because Ruby is not a statically typed language, you do not need to declare the type of vari-
able when assigning it. The following examples assign very different kinds of values to vari-
ables: a number, the string hello , and even an object. There is no need to tell Ruby the kind
of content that will be stored in a variable before assigning values:
a = 1
b = 'hello'
c = Object . new
Search WWH ::




Custom Search