Best Practices

Ruby Style Guide

Rails Testing Best Practices

Comment

ruby
# Single line comment

# Multiple
# line
# comment

Variable

ruby
stuff = "stuff"

String

Stings are mutable in Ruby

ruby
"Single line string"

HERE Doc

HERE are used for multi-line strings

ruby
# Old style - Ruby < 2.3 keep white space preceding string.
stuff = <<-DOC
  Stuff and thing.
  More stuff and things
DOC
#=> "  Stuff and thing.\n  More stuff and things\n"

# Squiggly line style - Ruby >= 2.3 strips preceding white space
stuff = <<~DOC
  Stuff and thing.
  More stuff and things
DOC
#=> "Stuff and thing.\nMore stuff and things\n"

Symbol

Symbols are similar to strings except they are immutable

ruby
:stuff

Integer

ruby
42

Boolean

ruby
true

# or

false

Array

ruby
["stuff", "things"]

Hash

ruby
# Old syntax - Ruby < 1.9
{:stuff_key => "stuff_value", :things_key => "things_value"}

# New syntax - Ruby >= 1.9
{stuff_key: "stuff_value", things_key: "things_value"}

For Loop

ruby
# Iterate array with a block
things.each do |thing|
  puts "#{thing}"
end

# One line block syntax for short code blocks
things.each {|thing| puts "#{thing}"}

# Iterate hash
stuff.each do |key, value|
  puts "#{key} #{value}"
end

While Loop

ruby
i = 1
while i < 42 do
  puts(i)
  i += 1
end

If, Elsif, Else

ruby
if 1 > 42
  puts "One"
elsif 42 < 1
  puts "The answer"
else
  puts "Maths is fun"
end

Function

ruby
def stuff
  # The last element in a function is returned automatically
  ["stuff", "more stuff", "other stuff"]
end

Class

ruby
class StuffAndThings
  attr_reader :stuff # Getter only
  attr_writer :things # Setter only
  attr_accessor :blah # Getter and Setter
  def initialize(stuff, things, blah)
    @stuff = stuff
    @things = things
    @blah = blah
  end
end
# ruby