I want something like "hey there" to turn into, for example, #316583
.
I want a string of any length to be "boiled down" so to speak to a hex color. I'm at loss even where to start.
I was thinking, an MD5 hash of every string is different - but how to turn that hash into a hex color number?
You can just take a few first digits:
require 'digest/md5'
color = Digest::MD5.hexdigest('My text')[0..5]
You can mod the md5 value by 2^24 and print that result in hex with a # sign before it.
Here's a bad way without the MD5, that gives very low values on short strings, but shows the idea:
sprintf("#%06x", ("asdf".sum % (256*256*256)))
output:
ruby-1.9.2-p290 :032 > sprintf("#%06x", ("asdf".sum % (256*256*256)))
=> "#00019e"
Replace "asdf".each_byte.inject(:+)
with the MD5 value and you should be good!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With