Authors: Alexandre ZANNI

# Methods

# Defining and calling

def hi
    puts "Hi"
end

irb(main):017:0> hi
Hi
=> nil

# Method parameters

def hi(name)
    puts "Hi #{name}"
end

irb(main):018:0> hi("Tim")
Hi Tim
=> nil

# Default and optional parameters

# Default parameters
def hi(name="")
    puts "Hi #{name}"
end

irb(main):004:0> hi
Hi
=> nil
irb(main):005:0> hi("Roger")
Hi Roger
=> nil

# Without parentheses
def sum x,y
    puts x+y
end

irb(main):009:0> sum 3,9
12
=> nil

# Optional parameters
def method(*arg)
    puts arg
end

irb(main):015:0> method(1)
1
=> nil
irb(main):016:0> method(1,"toto")
1
toto

# Return values from methods

def min(arr)
    return arr.min
end

irb(main):027:0> min([1,5,2,6])
=> 1

# Default return
def append(text)
    text = "#{text}!!!"
end

irb(main):036:0> append("magic")
=> "magic!!!"

# Return array
def sqr(x,y,z)
    return x**2,y**2,z**2
end

irb(main):041:0> sqr(2,7,9)
=> [4, 49, 81]

# Chaining methods
irb(main):050:0> [8,5,9,4.5,7].min.**(2).ceil
=> 21

# Methods as argument
def reverse(text)
    text.reverse
end

def print_reverse(text)
    "Reverse: #{text}"
end

irb(main):055:0> print_reverse(reverse("some text"))
=> "Reverse: txet emos"

# Variable scope

# Local variables
def add(x,y)
    x + y
end
puts y
# output: undefined local variable or method `y' for main:Object (NameError)

# Global variables
$y = 12
def add(x)
    x + $y
end
puts add(7)
# output: 19

# Recursion

def fact(n)
    if n <= 1
        1
    else
        n * fact(n - 1)
    end
end

irb(main):008:0> fact(5)
=> 120

# infinite recursion
def fact(n)
    n * fact(n - 1)
end

irb(main):012:0> fact(5)
SystemStackError: stack level too deep