RailsBrasil
Ruby

Referência rápida

Livro do Matz
http://www.math.hokudai.ac.jp/~gotoken/ruby/ruby-uguide/uguide00.html

Variáveis

$      variável global
@    variável de instância
[a-z]    variável local
[A-Z]    constante

A única exceção são as pseudo-variáveis, parece locais mas são constantes. São só duas, então não tem confusão.

self   o objeto em execução no momento
nil    valor `sem sentido' (para false, falso)

Núméricas

x = -100         # Fixnum
y = 15_000_000   # Bignum
z = 10.22        # Float
x, y, z = 0x10, 0b10, 010
x => hexadecial
y => binário
z => octal

Strings

a = "Puta que pariu" 
 b = "ha" * 5   # => hahahahaha
 c = "#{a}, meu gato pôs um ovo"

Symbols

a = :a
r = :rock

Arrays

a = ["zapata","zumbi","lampião"]
b = %w{zapata zumbi lampiao]
c = [4,5,6]

Hashes

a = {1 => 'Mac', 2 => 'Linux', 3 => 'Windows'}

Ranges

x = 1..5    # 1,2,3,4,5
y = 1...5   # 1,2,3,4

Especiais

$!              error message
   $@              position of an error occurrence
   $_              latest read string by `gets'
   $.              latest read number of line by interpreter
   $&              latest matched string by the regexep.
   $1, $2...       latest matched string by nth parentheses of regexp. 
   $~              data for latest matche for regexp
   $=              whether or not case-sensitive in string matching
   $/              input record separator
   $\              output record separator
   $0              the name of the ruby scpript file
   $*              command line arguments for the ruby scpript
   $$              PID for ruby interpreter
   $?              status of the latest executed child process

Métodos

def fala_oi_mal_educado
  puts "Oi!" 
end
def somador(x,y)
  x + y
end

Loops

5.times { puts "Ruby manda" }
10.times do |i|
  puts i
end
i=0
while(i<10)
 puts i
 i+=1
end

If

if true
  puts "Fala garoto!" 
end
x = 5
case x
  when 1: puts "O x da questão é 1" 
  when 1: puts "O x da questão é 2" 
  when 3..9: puts "O x da questão está entre 3 e 9" 
  else: "X-Frango

Classes

class Carro
  def initializer
  end
end
def buzinar
  puts "pééééééééééé" 
end

Herança

class Passaro
  def voar
    puts "batendo asa e voando!" 
  end
end
class Pinguim < Passaro
  def voar
   fail "pinguim nao voa" 
  end
end
ticotico = Passaro.new
ticotico.fly
tux = Pinguim.new
tux.fly

Módulos

Mixins

Procs

Threads

Test