Skip to content
headius edited this page Dec 29, 2012 · 1 revision

Literals

# All standard Ruby forms work (without interpolation)
puts "str"
puts 'str'
puts %q[str]
puts %Q[str]
puts <<EOS
heredoc
EOS

Flow control

if true
  puts true
  while false
    puts 'huh?'
  end
else
  puts false
end

Simple method definition and invocation

def foo
  "hello"
end

puts foo # prints out "hello"

Math

def fib(a)
  if a < 2
    a
  else
    fib(a - 1) + fib(a - 2)
  end
end

puts fib(40) # prints "102334155"

Classes

class Foo
  def initialize
    puts 'init!'
  end

  def bar
    puts 'bar!'
  end
end

f = Foo.new # prints "init!"
f.bar # prints "bar!"

method_missing

class Foo
  def method_missing(name, args)
    puts name
  end
end

f = Foo.new
f.bar # prints "bar"
f.baz # prints "baz"
Clone this wiki locally