怎么样:
# encoding:UTF-8
require 'rubygems'
require 'json'
def constrained_json(limit, a, b, c)
output, size, hash = nil, 0, { :a => a, :b => b, :c => c}
[:c, :b, :a, :a].each do |key|
output = hash.to_json
size = output.bytesize
break if size <= limit
# on 1.9:
# hash[key] = hash[key][0...(limit - size)]
# on 1.8.7
hash[key] = hash[key].unpack("U*")[0...(limit - size)].pack("U*")
end
raise "Size exceeds limit even after truncation" if size > limit
output
end
38.downto(21) do |length|
puts "# #{constrained_json(length, "Qué te", "parece", "eh?")}"
end
# {"a":"Qué te","b":"parece","c":"eh?"}
# {"a":"Qué te","b":"parece","c":"eh"}
# {"a":"Qué te","b":"parece","c":"e"}
# {"a":"Qué te","b":"parece","c":""}
# {"a":"Qué te","b":"parec","c":""}
# {"a":"Qué te","b":"pare","c":""}
# ...
# {"a":"","b":"","c":""}
# test.rb:14:in `constrained_json': Size exceeds limit even after truncation (RuntimeError)