alex.bour alex.bour - 5 months ago 23x
Ruby Question

Ruby get the size in bytes of an array

I would like to obtain the size in bytes of the content of an array (items) in ruby.

I fill my array like this:

@records.each do |record|
items << { :table => table, :id =>, :lruos => record.updated_at }

In fact, I want to force sending the Content-Length of this array when I serialize it in JSON:

respond_to do |format|
#response['Content-Length'] = items.to_s.size
format.json { render :json => { :success => "OK", :items => items } }

So any idea to do this could be interesting.
(for a reason I don't know the content length is not sent, so I want to force it)

I use Rails 3.0.5.


Like WTP said, you probably intend on returning the size of the JSON representation instead of ruby representation of the array, because the JSON is the actual response to the browser. You can do this by encoding beforehand (yielding a string) and then checking its size.

response['Content-Length'] = ActiveSupport::JSON.encode(items).size

More about JSON serialization and rails