What is recursion and how does it work?

后端 未结 4 1054
南方客
南方客 2020-12-12 14:27

Could someone please explain what exactly recursion is (and how it works in Ruby, if that\'s not too much to ask for). I came across a lengthy code snippet relying on recurs

4条回答
  •  失恋的感觉
    2020-12-12 14:39

    Typically recursion is about method calling themselves, but maybe what you encountered were recursive structures, i.e. objects referring to themselves. Ruby 1.9 handles these really well:

    h = {foo: 42, bar: 666}
    parent = {child: {foo: 42, bar: 666}}
    h[:parent] = parent
    h.inspect # => {:foo=>42, :bar=>666, :parent=>{:child=>{...}}}
    
    x = []
    y = [x]
    x << y
    x.inspect # => [[[...]]]
    x == [x]  # => true
    

    I find that last line is quite wicked; I blogged about this kind of issues with comparison of recursive structures a couple of years ago.

提交回复
热议问题