I'd like to set a consistent color for a user's default avatar background, according to the following rules:
I'm thinking of something along these lines:
But I can't quite figure out how to go about it. Any suggestions? If I could do it without getting any extra gems that would be ideal. I already use MD5 for some hashing stuff.
NOTE: this isn't a security issue, it's just a bit of fun, so if two different names end up generating the same color once in a while it doesn't matter too much, but generally it would be nice to have the color values as varied as possible.
You could build an MD5-hash of the user's name via:
require 'digest'
name = 'foo'
digest = Digest::MD5.digest(name)
#=> "\xAC\xBD\x18\xDBL\xC2\xF8\\\xED\xEFeO\xCC\xC4\xA4\xD8"
Extract the first three 16-bit integers:
values = digest.unpack('SSS')
#=> [48556, 56088, 49740]
And map these 0..65535 values to 0..200:
values.map { |i| i * 201 / 0x10000 }
#=> [148, 172, 152]