こういうjsonへのシリアライズ方法が書かれてないクラスを使って、to_jsonすると

#!/usr/bin/env ruby
require 'rubygems'
require 'json'

class User
attr_reader :id, :name
def initialize(id, name)
@id = id
@name = name
end
end

users = Array.new
['user1', 'user2', 'shokai'].each_with_index{|name,id|
users.push User.new(id, name)
}

puts users.to_json


クラス名が出てきてしまう
["#<User:0x007fc17b8bda50>","#<User:0x007fc17b8bda28>","#<User:0x007fc17b8bda00>"]


JSON implementation for Rubyに、to_json(*a)を定義しろって書いてあった
#!/usr/bin/env ruby
require 'rubygems'
require 'json'

class User
attr_reader :id, :name
def initialize(id, name)
@id = id
@name = name
end

## JSON作る
def to_json(*a)
{
:id => @id,
:name => @name
}.to_json(*a)
end
end

users = Array.new
['user1', 'user2', 'shokai'].each_with_index{|name,id|
users.push User.new(id, name)
}

puts users.to_json


ちゃんと出てきた
[{"id":0,"name":"user1"},{"id":1,"name":"user2"},{"id":2,"name":"shokai"}]