Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a color based on an alphanumeric string using Ruby?

Tags:

ruby

hex

colors

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?

like image 942
dsp_099 Avatar asked Jun 09 '13 08:06

dsp_099


2 Answers

You can just take a few first digits:

require 'digest/md5'
color = Digest::MD5.hexdigest('My text')[0..5]
like image 75
Yossi Avatar answered Oct 20 '22 23:10

Yossi


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!

like image 2
xaxxon Avatar answered Oct 20 '22 23:10

xaxxon