Ruby style programming was built on two simple ideas:
- Code must be crystal clear
- Code must be concise
Example:
# Author: Russ Olsen
#
# Class that models a plain text document, complete with title
# and author:
#
# doc = Document.new( 'Hamlet', 'Shakespeare', 'To be or...' )
# puts doc.title
# puts doc.author
# puts doc.content
#
# Document instances know how to parse their content into words:
#
# puts doc.words
# puts doc.word_count
#
class Document
attr_accessor :title, :author, :content
def initialize(title, author, content)
@title = title
@author = author
@content = content
end
def words
@content.split
end
def word_count
words.size
end
def method_to_be_overriden; end
def document_spelling
words.each { |n| puts "The word is #{n}" }
end
end
Things to note about the snippet code above:
- Ruby indentation convention: two space per level (don't ever use tab spaces for Ruby indentation)
- Anything following a # in the code is a comment. Multiline comments can starts with =begin and finish with =end, but Rubyst convention are to use #
- Good Ruby code must speak for itself: don't insert comment simply because you always put a comment somewhere.
- Use comments for how to comments: tell me how to use the thing and remember that examples are always welcome.
- Avoid comments to explain how the code works: they tend to make a badly written code somewhat comprehensible.
- Replace how code works comments by class, methods and variables refactoring. (Remember, good code is like a good joke: It needs no explanation).
- Use lowercase_words_separated_by_underscores when you refer to methods, arguments and variables identifiers.
- Use camel case when you refer to classes identifiers.
- Camel case can be used for constants identifiers too. But a convention is to choise for ALL_UPPERCASE_WITH_UNDERSCORE
- Use parentheses only when indeed needed. Usually for multiple arguments methods (both in method definitions and calls) or method calling with complex expression.
- Don't use parentheses for conditional statements.
- Use several Ruby statements onto a single line, split by semicolon between statements for empty or small classes and methods.
- Code blocks convention: block with one statement, use parentheses to delimit code block. Otherwise, use do/end form.
- The exception for the convention above are too long one statement blocks. For those cases, you must use do/end to delimit code block.