Search code examples
rubyhashruby-1.9.3

Serialize Ruby Hash in Batches


I need to serialize a large hash into the form key1=value1, key2=value2, key3=value3.... I need to do it for every 100 keys, and send the string to a remote server.

def batch_serialize(h, size)
  h_as_a = h.to_a
  while h_as_a.length > 0 do
    batch = Hash[h_as_a.slice!(0,size)]
    serialized = []
    batch.each_pair { |k,v| serialized += "#{k}=#{v}" }
    transmit(serialized.join(', '))
  end
end

There should be an easier way to get chunks of an Hash (or to split the hash into multiple, smaller hashes) and operate on them. Am I missing something?


Solution

  • I would use Enumerable#each_slice, doing as below

    def batch_serialize(h, size)
      h.each_slice(size) do |rows|
        serialized = rows.map { |k,v| "#{k}=#{v}" }
        transmit(serialized.join(', '))
      end
    end