I need to create a signature string for a variable in Ruby, where the variable can be a number, a string, a hash, or an array. The hash values and array elements can also be any of these types.
This string will be used to compare the values in a database (Mongo, in this case).
My first thought was to create an MD5 hash of a JSON encoded value, like so: (body is the variable referred to above)
def createsig(body)
Digest::MD5.hexdigest(JSON.generate(body))
end
This nearly works, but JSON.generate does not encode the keys of a hash in the same order each time, so createsig({:a=>'a',:b=>'b'})
does not always equal createsig({:b=>'b',:a=>'a'})
.
What is the best way to create a signature string to fit this need?
Note: For the detail oriented among us, I know that you can't JSON.generate()
a number or a string. In these cases, I would just call MD5.hexdigest()
directly.
x.hash
(or a combination ofx.hash
andx.class
) if you don't need them to be consistent across processes. – Overburden