A Live Developer Journal

Documenting Ruby Code With Friendly Usage Examples

Ruby has a really cool feature where you can add code that only runs when it's enclosing file is run directly (as opposed to being run from a different code or test file that requires it). All you need to do is wrap the optional code in the following block:

  # Your optional code here

I like to use this as an opportunity to add usage examples to demonstrate the functionality of the main code. For example, the main code in my "project.rb" class file is:

  class Project
  attr_reader :name, :purpose, :dependencies

  def initialize(name = "Project", purpose = "No purpose")
    @name = name
    @purpose = purpose
    @dependencies = []

  def add_dependency(dependency)
    @dependencies << dependency

  def remove_dependency(dependency)

While it's fairly easy to figure out what's going on with this class, it's a little more difficult to imagine it working in the context of a real-world program. The usage examples at the bottom of the file bring it to life, which makes it easier to understand why you might want to use it, and how it can be adapted to your own purposes.

# Run usage examples only when current file is run directly
if __FILE__==$0

  # ----- Example Data -----

  name = "Knit a bear"
  purpose = "Birthday gift"
  dependencies = ["Knitting Pattern", "Yarn", "Pizza"]

  # ----- Usage Examples -----

  # ✨ Create new project with a name and purpose
  bear_project = Project.new(name, purpose)

  dependencies.each do |dependency|
    # ✨ Add a project dependency

  # ✨ Remove project dependencies

  # ----- Expected Output -----

  puts bear_project.name # => Knit a bear
  puts bear_project.purpose # => Birthday Gift
  puts bear_project.dependencies # Knitting Pattern\nYarn

When you run the project.rb file directly (ruby project.rb), you should get the following output:

Knit a bear
Birthday Gift
Knitting Pattern

When you run a file that requires and uses the project.rb file (e.g. ruby project_spec.rb or ruby roadmap.rb. Then the usage examples won't run and you won't see the above output in the console.