Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 11th, 2012  |  syntax: None  |  size: 0.51 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. What is Ruby recursion and how does it work?
  2. >> def countdown(n)
  3. ..   return if n.zero? # base case
  4. ..   puts n
  5. ..   countdown(n-1)    # getting closer to base case
  6. ..   end #=> nil
  7. >> countdown(5) #=> nil
  8. 5
  9. 4
  10. 3
  11. 2
  12. 1
  13.        
  14. def fib(n)
  15.   return n if (0..1).include? n
  16.   fib(n-1) + fib(n-2) if n > 1
  17. end
  18.        
  19. h = {foo: 42, bar: 666}
  20. parent = {child: {foo: 42, bar: 666}}
  21. h[:parent] = parent
  22. h.inspect # => {:foo=>42, :bar=>666, :parent=>{:child=>{...}}}
  23.  
  24. x = []
  25. y = [x]
  26. x << y
  27. x.inspect # => [[[...]]]
  28. x == [x]  # => true