Lesson Weekend

Source Code Layout


Spaces and Indentation

  • Use two spaces per indentation level. Indentation levels in Ruby are inside classes, methods, if/else statements, and loops. In HTML it would be inside of tags.
# Bad - four spaces.
    def some_method()
end

# Bad - indentation levels don't line up.
  def some_method()
end

# Good - two spaces.
def some_method()
  # Write code here.
end

Calling Methods

  • For now, use () after methods, even if they don't have an argument. (You can call methods without () as well, but adding () can help increase readability.)
  • No spaces after (, [ or before ]. ).
"Some String".method_name("argument")

Defining Methods and Variables

  • Use empty lines between method definitions within a class.
  • Blocks of code should have no extra lines in them. For example, a define_method block should be single-spaced.
  • Use spaces around the = operator when assigning values to variables.
  • Avoid explicitly using self inside of a method definition, unless it is the argument to a method. Use the implicit self.
# Not as good.
def some_method
  self.split()
end

# good
def some_method
  split()
end

Collections

  • Avoid a comma after the last item in an Array or Hash.
# bad
num_array = [1,2,3,]

# good
num_array = [1,2,3]

Naming Conventions


General

  • Always use English when naming.
  • Use snake_case for symbols, methods, variables, files and folders. snake_case means using all lowercase words, separated with an underscore.
  • Do not use shortened words for variable names, as the meaning of the abbreviation could be unclear.
  • Avoid generic naming of variables like output or result or array or hash since these types of names apply to MANY elements.

Collections

  • Use plural nouns when naming arrays.
  • If you are looping through an array with an each() loop, use the singular form of the array name as the parameter of the loop.

Methods

  • Names of methods that return a boolean value should end in a question mark (i.e. Array#empty?). Methods that do not return a boolean should not end in a question mark.
  • Methods that modify the receiver or self should end with an exclamation mark (i.e. String#capitalize!()).

Classes

  • Classes are capitalized and when they contain more than one word and are written in upper camel case (i.e. NilClass).

Comments


  • Write clear, descriptive code that is considered self-documenting and avoid using comments, unless variable naming and flow do not convey all of the details that are needed. Ideally, your code should need no explanation.
  • Use one space between the leading # character of the comment and the text of the comment.
  • Comments longer than one word are capitalized and use correct English punctuation.
  • Avoid superfluous comments and comments to explain bad code. Refactor your code to make it self-explanatory.

Lesson 8 of 10
Last updated August 7, 2022