Musings of an 8-bit Vet

A Student Coders Tech Diary

Matters of Style

As we are starting to write code, it becomes apparent that some code just looks better than other code. I’m pretty sure the Ruby interpreter doesn’t care, but source code is really a document of the product that the code produces so it is important that it be readable and understandable to others.

Ruby is pretty expressive, and it seems to offer a lot of flexibility with the syntax. This could lead to a lot of variation in style. Just as there are standards for style in the production of written works, so there are for programmers.

For Ruby that style guide seems to be: BBatsov’s Ruby Style Guide.

It’s an envolving document with a lot of examples of good and bad coding style, some of which I am certain are parts of large philosophical debates. In any event as a new Rubyist I feel it is important to develop good habits. I read through the whole document and here some picks for new programmers to be aware of when writing code, based on the sort of code we are writing now.

All examples courtesy of BBatsov.

Limit lines to 80 characters.

Avoid trailing whitespace.

Use spaces around operators, after commas, colons and semicolons, around {and before }. Whitespace might be (mostly) irrelevant to the Ruby interpreter, but its proper use is the key to writing easily readable code.

1
2
3
4
sum = 1 + 2
a, b = 1, 2
1 > 2 ? true : false; puts 'Hi'
[1, 2, 3].each { |e| puts e }

No spaces after (, [ or before ], ).

1
2
some(arg).other
[1, 2, 3].length

Use empty lines between defs and to break up a method into logical paragraphs.

1
2
3
4
5
6
7
8
9
10
11
def some_method
  data = initialize(options)

  data.manipulate!

  data.result
end

def some_method
  result
end

Use spaces around the = operator when assigning default values to method parameters:

1
2
3
4
5
6
7
8
9
# bad
def some_method(arg1=:default, arg2=nil, arg3=[])
  # do something...
end

# good
def some_method(arg1 = :default, arg2 = nil, arg3 = [])
  # do something...
end

Add underscores to large numeric literals to improve their readability.

1
2
3
4
5
# bad - how many 0s are there?
num = 1000000

# good - much easier to parse for the human brain
num = 1_000_000

Don’t use block comments. They cannot be preceded by whitespace and are not as easy to spot as regular comments.

1
2
3
4
5
6
7
8
9
# bad
== begin
comment line
another comment line
== end

# good
# comment line
# another comment line

That’s probably enough to get started. There is also a very useful gem RuboCop that will tell you where you are diverging from these recommendations.