User Tools

Site Tools


coding:ror

Ruby

before coding

style guide

ruby style guide
SOLID OO-Coding principles


Short style guide summary:

  • CamelCase for classes and modules
  • snake_case for methods, files and directories
  • SCREAMING_SNAKE_CASE for constants
  • all names, variables are in english
  • 2 spaces indentation
  • one expression per line (therefore methods always have at least 3 lines)
  • no line ending (no . ; : or whatever)
  • avoid line continuation (done with \ - ok for string concatenation)
  • end each file with a newline
  • {…} for single line / do end syntax for multiline
  • “.self” is only required when calling a self write accessor
  • _unused_var / write a “_” in front of an unused var

Setup for a class

class Person
  # extend and include go first
  extend SomeModule
  include AnotherModule
 
  # inner classes
  CustomErrorKlass = Class.new(StandardError)
 
  # constants are next
  SOME_CONSTANT = 20
 
  # afterwards we have attribute macros
  attr_reader :name
 
  # followed by other macros (if any)
  validates :name
 
  # public class methods are next in line
  def self.some_method
  end
 
  # followed by public instance methods
  def some_method
  end
 
  # protected and private methods are grouped near the end
  protected
 
  def some_protected_method
  end
 
  private
 
  def some_private_method
  end
end

Installing gems

Use the following code to install gems:

gem install <gem name>

On a mac, never use the command sudo for installing gems!


Expressions

String = “Text” (some part of a phrase)
Integer = 2 (full numbers)
Float = 2.4 (decimal numbers)
Array = [1,2,“three”] (an array of values)
Hash = {key: “value”} (key value pairs)


basic methods

basics

  • and = &&
  • or = ||
  • %w(one two three) for a new array with strings without spaces
  • %i(one two three) for a set of symbols

shorthand self assignment operators

x += y meaning (x = x + y)
x -= y meaning (x = x - y)
x *= y meaning (x = x * y)
x **= y meaning (x = x**y)
x /= y meaning (x = x / y)
x ||= y meaning (x = x || y)
x &&= y meaning (x = x && y)

converting

  • To string: to_s
  • To integer: to_i
  • To float: to_f
  • To symbol: to_sym
  • Array to hash: to_h
  • Hash to array: to_a

splat operator (multiple arguments)

def twenty_one?(*x)
x.reduce {|sum, n| sum + n} == 21
end

x can be a bunch of numbers from 1 to n (n = any number you want)


formatting your output

.sprintf #sprintf will let you change the output in multiple ways you want #format will do the same thing.

sprintf("%04d", 3)

will output you a number like 0003


getting values based on a key (fetch)

Problem: get all values from the items array, according to the index provided. If the index is not present, return the default value.

def solution(items, index, default_value)
  items.fetch(index, default_value)
end

If else statements

One line

result = some_condition ? something : something_else


Multi line

result =
  if condition
    x
  else
    y
  end

Loops

While and until loops - preferably on one line

#for positive conditions
do_something while some_condition
 
#for negative conditions
do_something until some_condition


Loop with break

loop do
  puts val
  val += 1
  break unless val < 0
end


Loop with an if statement

[0, 1, 2, 3].each do |item|
  next unless item > 1
  puts item
end

use next instead if an if statement inside the each block.


Hashes

setting multiple variables from multiple keys

email, username = data.values_at('email', 'nickname')

Variables

  • local variables: lowercase letter or _
  • instance variables: starting with @
  • class variables: starting with @@
  • global variables: starting with $
my_variable = "something" 

(variable = placeholder for string, integer etc.)

Local Variables
Local Variables: Local variables are the variables that are defined in a method. Local variables are not available outside the method. You will see more detail about method in subsequent chapter. Local variables begin with a lowercase letter or _.


Instance Variables
Instance Variables: Instance variables are available across methods for any particular instance or object. That means that instance variables change from object to object. Instance variables are preceded by the at sign (@) followed by the variable name.


Class Variables
Class Variables: Class variables are available across different objects. A class variable belongs to the class and is a characteristic of a class. They are preceded by the sign @@ and are followed by the variable name.


Global Variables
Global Variables: Class variables are not available across classes. If you want to have a single variable, which is available across classes, you need to define a global variable. The global variables are always preceded by the dollar sign ($).


Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 40 bytes) in /home_p2/d/o/domidesign.ch/htdocs/domicode.com/wiki/lib/plugins/authplain/auth.php on line 340