title: convert Ruby array of class into JSON
body: <p>I have a Ruby data structure as such:</p>
  
  <pre><code>class Albums
      attr_accessor :title, :url
  
      def initialize(title, url)
          @title = title
          @url = url
      end
  end
  
  class Albumlist &lt; Albums
      attr_accessor :id, :albums
  
      def initialize(id)
          @id = id
          @albums = Array.new
      end
  end
  </code></pre>
  
  <p>And I made an array of <em>Albumlist</em> which looks like (using .inspect method):</p>
  
  <pre><code>[#&lt;Albumlist:0x8db6390 @id="abc",@albums=[
       #&lt;Albums:0x8db6098 @title="123", @url="test"&gt;,
       #&lt;Albums:0x8db5fe4 @title="456", @url="test"&gt;
   ]&gt;,
   #&lt;Albumlist:0x8f4042c @id="def", @albums=[
       #&lt;Albums:0x8f49f2c @title="Untitled Album", @url="test"&gt;
   ]&gt;
  ]
  </code></pre>
  
  <p>I am not sure if this array looks okay but once I used the method .to_json or JSON.generate() on this array, all I get is:</p>
  
  <pre><code>["#&lt;Albumlist:0x8db6390&gt;","#&lt;Albumlist:0x8f4042c&gt;"]
  </code></pre>
  
  <p>It looks like Ruby returns the "reference" to the object instances.
  I want to convert this array in JSON which should look like</p>
  
  <pre><code>[
      {
              "id":"abc"
              "albums":[
                      {
                              "title":"123",
                              "url":"test"
                      },
                      {
                              "title":"456",
                              "url":"test"
                      }
              ]
      },
      {
              "id":"def"
              "albums":[
                      {
                              "title":"Untitled Album",
                              "url":"test"
                      }
              ]
      }
  ]
  </code></pre>
  
  <p>and I believe I am missing something, such as converting the array into some kind of intermediate object?</p>
  
  <p><strong>EDIT: Alternate Solution</strong></p>
  
  <p>Define a to_json method in class Albumlist as such:</p>
  
  <pre><code>def to_json(*a)
      {
          "id" =&gt; @id,
          "albums" =&gt; @albums
      }.to_json(*a)
  end
  </code></pre>
  
  <p>And use it instead..</p>