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
endUse # 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- Class names should be in
Camel Caselike: DocumentParser, Cars, ReadingTimeAnalyser. - Variables and Methods should be in
snake caselike: word_counter, say_hello. - Constants can be either
Upper Camel CaseorUpper Snake Caselike: STUDENTSCOUNT, TOTAL_BULBS.
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"
endThe 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; enddef call_home; endCode 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