In method parameter, we can write any kind of assignment statements in Ruby.

The most popular default parameter is literals:

```
def f(a, b = :aaa)
...
end
```

Rarely we can see method calls in default parameter:

```
def f(a, b = Array.new)
...
end
def g(a, b = 1 + 2)
...
end
```

We can refer the other precedent parameters:

```
def f(a, b = a * 2)
b
end
p f(10) #=> 20
```

We can write more complicated code there.

```
def g(a, b = (def j; end; 1))
[a, b]
end
```

This code works tricky. After `g`

was called *without* the second argument,
method `j`

is defined.

We also can write recursive call there.

```
def fib(n, x = n == 0 ? 0 : n == 1 ? 1 : fib(n-2) + fib(n-1))
x
end
p fib(10) #=> 55
p fib(10, :hehehe) #=> :hehehe
```

## No comments:

## Post a Comment