# Ruby tailcall optimizes?

**URL:** <https://www.ruby-forum.com/t/ruby-tailcall-optimizes/147993>\
**Category:** Ruby\
**Created:** [September 8, 2008, 5:01am UTC](https://www.ruby-forum.com/t/ruby-tailcall-optimizes/147993 "2008-09-08T05:01:36Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![cnb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/9dc877/32.png) [@cnb](https://www.ruby-forum.com/u/cnb)\
**Post date:** [September 8, 2008, 5:01am UTC](https://www.ruby-forum.com/t/ruby-tailcall-optimizes/147993/1 "2008-09-08T05:01:36Z")

</div>

Hmm this was a nice surprise. it seems Ruby does tailcall-  
optimization? One up for Ruby on Python.

Is there a way to have optional arguments in Ruby? Then I could make  
it one function instead of wrapping them.

irb(main):011:0\> fact(12000)  
fact(12000)  
1201858406751094813215537862229…  
irb(main):012:0\> fac(12000)  
fac(12000)  
SystemStackError: stack level too deep  
from c:/ruby/Progs/blandat/learn.rb:34:in `fac' from c:/ruby/Progs/blandat/learn.rb:34:in`fac’  
from (irb):12  
irb(main):013:0\>

def fact(n)  
def f(n, acc)  
if n \> 0  
then f(n-1, n\*acc)  
else acc  
end  
end  
f(n, 1)  
end

def fac(n)  
if n \> 0  
then n \* fac(n-1)  
else 1  
end  
end

---

<div class="post-metadata">

**Author:** ![cnb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/9dc877/32.png) [@cnb](https://www.ruby-forum.com/u/cnb)\
**Post date:** [September 8, 2008, 5:04am UTC](https://www.ruby-forum.com/t/ruby-tailcall-optimizes/147993/2 "2008-09-08T05:04:32Z")

</div>

wow this was nice and elegant and i can even call it with fac 5 withou  
parenthesis. .

def fac(n, acc=1)  
if n \> 0  
then fac(n-1, n\*acc)  
else acc  
end  
end

---

<div class="post-metadata">

**Author:** ![cnb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/9dc877/32.png) [@cnb](https://www.ruby-forum.com/u/cnb)\
**Post date:** [September 8, 2008, 1:54pm UTC](https://www.ruby-forum.com/t/ruby-tailcall-optimizes/147993/3 "2008-09-08T13:54:15Z")

</div>

2008/9/8 cnb [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> Hmm this was a nice surprise. it seems Ruby does tailcall-  
> optimization?

It doesn’t.

13:51:03 ~$ ruby -e ‘def t(a)a\>0?t(a-1):a;end;t 1\_000\_000’  
-e:1:in `t': stack level too deep (SystemStackError) from -e:1:in `t’  
from -e:1  
13:51:39 ~$ ruby19 -e ‘def t(a)a\>0?t(a-1):a;end;t 1\_000\_000’  
-e:1:in `t': stack level too deep (SystemStackError) from -e:1:in `t’  
from -e:1:in `t' from -e:1:in `t’  
from -e:1:in `t' from -e:1:in `t’  
from -e:1:in `t' from -e:1:in `t’  
from -e:1:in `t' ... 7264 levels... from -e:1:in `t’  
from -e:1:in `t' from -e:1:in `t’  
from -e:1:in `’

> Is there a way to have optional arguments in Ruby?

Did you read the documentation?

robert
