Every programming community quickly converges on a style, an accepted set of idioms. Programming is all about communication and knowing those idioms are key to being a successful programmer in that community.
Ruby style of programming:
- Code should be crystal clear, it should shout its intent
- Good code is also concise
Ruby indentation convention:
- 2 spaces per level
- Never use tabs to indent
Ruby comments:
- Anything following a
#
in the code is a comment - Good Ruby code should speak for itself, so go easy on the comments
- Avoid boilerplate comments
- Comments explaining how to use your software are great to have
- Just so you know, multiline comments in Ruby are delimited by =begin and =end but they are hardly used
- Above all, remember that good code is like a good joke: It needs no explanation
Naming things:
- With a few notable exceptions, you should use
lowercase_words_separated_by_underscores
- Exceptions include modules, classes and constants
- Module and classes should be
CamelCased
- And constants should use
UPPERCASE_WORDS_SEPARATED_BY_UNDERSCORES
- Module and classes should be
Parentheses:
- Optional
- We don't do empty argument lists
puts 'No parentheses'
- We usually leave them off around the conditions in control statements
- Occasionally forbidden
Examples of having more than one statement per line:
# Example 1
puts doc.title; puts doc.author
# Example 2
class DocumentException < Exception; end
# Example 3
def no_op; end
Folding up code blocks:
- If your block consists of a single statement, fold the whole statement into a single line and delimit the block with braces.
- If you have a multi-statement block, spread the block out over a number of lines, and use the do/end form.
When formatting code, always mix in a pinch of pragmatism.
The best way to learn to write idiomatic Ruby code is to read idiomatic Ruby code.
- The Ruby Standard Library
- Set
- Little Known Ways to Ruby Mastery by James Edward Gray II
- Ruby: Designers, Producers and Consumers
- When do instance variables come into scope?
See Instance Variables in Ruby.
Trying to reference an uninitialized instance variable will return nil
rather than raise an exception.
@b #=> nil
@b.nil? #=> true
@b = 5 #=> 5
@b.nil? #=> false
- Where is the source file for set.rb located?
On my machine it's at: ~/.rvm/src/ruby-1.9.3-p429/lib/set.rb
.
Great notes! Please consider uploading your notes to SciencePad
Here is the Document Class from the book.