Skip to content

Instantly share code, notes, and snippets.

@skippednote
Created February 12, 2014 19:25
Show Gist options
  • Select an option

  • Save skippednote/8962696 to your computer and use it in GitHub Desktop.

Select an option

Save skippednote/8962696 to your computer and use it in GitHub Desktop.
Based of learning from Eloquent Ruby.

Ruby

Indentation

Use 2 space. No tabs.

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
    word.size
  end
end

Comments

Use # in front of a line to comment it out. The code should be clear enough that there is no requirement for comments. Use it to explain how something can be used or how something is working. Try to minimize the need of comments by making the code consise and clear.

Remember, good code is like a good joke: It needs no explanation.
class Animal
    def walk
        # code to walk
    end

    def run
        puts 'Animal is running' # code to make an animal run
    end
end

Naming conventions

  • Class names should be in Camel Case like: DocumentParser, Cars, ReadingTimeAnalyser.
  • Variables and Methods should be in snake case like: word_counter, say_hello.
  • Constants can be either Upper Camel Case or Upper Snake Case like: STUDENTSCOUNT, TOTAL_BULBS.

Parentheses

Parentheses are optional in Ruby and this make the syntax clean and easy to read. We can pass arguments to a function without parentheses or optionally add them to avoid confusions. Function in Ruby are called without the () at the end of function name.

def method param1, param2
    puts "The total is #{param1} + #{params2}"
end

method 2, 3 # Can also be method(2, 3)
if words.size > 100
    puts "It's a paragraph"
end

Folding Lines

The prefered way of writing Ruby is to stick to single statement per line, however we can join several lines into one using ;. This is not recommened as it is decrese the readability of the code. Some of the common use cases for this can be empty classes and methods.

class Driver < Car; end
def call_home; end

Folding Code Blocks

Code block is a piece of code delimited by either curly braces ({}) or do end. The curly braces are used when there is just a single line of code and line of it is written in a single line. do end comes in handy when we have more than one line of code.

10.times { |n| puts 'The number is #{n}' }
10.times do |n|
  puts 'The number is #{n}'
  puts 'Twice the number is #{n*2}'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment