Ruby get the size in bytes of an array

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.


Alternatively, you can also do this by item.to_json.bytesize. This will give you the size of JSON string that is being sent.


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

Tags:

Arrays

Ruby