title: Recursive to_json in Ruby
body: <p>I have a simple class that overrides to_json to list the attributes in an array -</p>
  
  <pre><code>class MyClass
    def initialize(a, b)
      @a = a
      @b = b
    end
  
    def to_json(*opt)
      [@a, @b].to_json(*opt)
    end
  end
  </code></pre>
  
  <p>to_json works fine for an instance of the class -</p>
  
  <pre><code>irb&gt; m = MyClass.new(10, "abc")
  irb&gt; m.to_json
  =&gt; "[10,\"abc\"]"
  </code></pre>
  
  <p>But if I put the object in an array, my custom to_json does NOT get called -</p>
  
  <pre><code>irb&gt; [m].to_json
  =&gt; "[{\"a\":10,\"b\":\"abc\"}]"
  </code></pre>
  
  <p>I would expect to get the following output -</p>
  
  <pre><code>=&gt; "[[10,\"abc\"]]"
  </code></pre>
  
  <p>Another example - if I create another instance that contains the first instance</p>
  
  <pre><code>irb&gt; m2 = MyClass.new(20, m)
  irb&gt; m2.to_json
  =&gt; "[20,{\"a\":10,\"b\":\"abc\"}]"
  </code></pre>
  
  <p>What I expect is </p>
  
  <pre><code>=&gt; "[20,[10,\"abc\"]]"
  </code></pre>
  
  <p>Looks like to_json does not get called recursively. How to solve this?</p>
  
  <p>Thanks as always!!</p>
  
  <h2>Updates</h2>
  
  <p>This seems to work as expected on Ruby 1.9.1. Thanks Mladen!<br>
  I need to use 1.8.7. </p>