Ruby获取数组的字节大小

时间:2020-12-30 21:43:38

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

我想获得ruby中数组(项)内容的大小(以字节为单位)。

I fill my array like this:

我这样填充我的数组:

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

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

实际上,我想在JSON中对它进行序列化时强制发送此数组的Content-Length:

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

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.

我使用Rails 3.0.5。

2 个解决方案

#1


7  

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.

就像WTP所说,你可能打算返回JSON表示的大小而不是数组的ruby表示,因为JSON是对浏览器的实际响应。您可以通过预先编码(生成一个字符串)然后检查其大小来完成此操作。

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

More about JSON serialization and rails

有关JSON序列化和rails的更多信息

#2


1  

For those that are still wondering - I found this to work

对于那些仍在疑惑的人 - 我发现这个有用

ActiveSupport::JSON.encode(items).size.to_s

Which while its many years later - may help someone.

虽然多年后 - 可能会帮助某人。

#1


7  

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.

就像WTP所说,你可能打算返回JSON表示的大小而不是数组的ruby表示,因为JSON是对浏览器的实际响应。您可以通过预先编码(生成一个字符串)然后检查其大小来完成此操作。

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

More about JSON serialization and rails

有关JSON序列化和rails的更多信息

#2


1  

For those that are still wondering - I found this to work

对于那些仍在疑惑的人 - 我发现这个有用

ActiveSupport::JSON.encode(items).size.to_s

Which while its many years later - may help someone.

虽然多年后 - 可能会帮助某人。