skip to Main Content

I’m making a telegram bot and I would like for it to be able to give a hex code against a color name. I know there are a heck of a lot of rgb colors but I also know there is a wikipedia article with known color names and hex codes, if I could be able to get the pages as a json it would help. Also, if the json says hex code = color name how can I invert that? How can I search by the value and not the name?

3

Answers


  1. You could write your own Hash then Hash#invert it:

    color_to_hex = { red: 'ff0000', green: '00ff00', blue: '0000ff' }
    hex_to_color = color_to_hex.invert
    
    color_to_hex[:red] #=> "ff0000"
    hex_to_color['00ff00'] #=> :green
    

    Or without creating the inverse hash:

    colors_to_hex.key('00ff00') #=> :green
    
    Login or Signup to reply.
  2. You can try following :

    color_mappings = { 'yellow' => 'ffff00', 'red' => 'ff0000', 'green' => '00ff00', 'blue' => '0000ff' }
    

    The hash can be inverted as follow :

    inverted_color_mappings = color_mappings.invert
    

    output :

    {
        "ffff00" => "yellow",
        "ff0000" => "red",
        "00ff00" => "green",
        "0000ff" => "blue"
    }
    
    
    pattern = 'fff'
    inverted_color_mappings.select{ |k,v| k[pattern] }
    

    output :

    {
        "ffff00" => "yellow"
    }
    
    Login or Signup to reply.
  3. The other answers are fine. If you’re looking for a gem that’s already done the work for you, though, take a look at Color. Its Color::CSS[] method looks up a color by name and returns a Color::RGB object, which in turn has hex and html methods:

    require "color"
    
    aliceblue = Color::CSS["aliceblue"]
    puts aliceblue.hex
    # => f0f8ff
    puts aliceblue.html
    # => #f0f8ff
    

    Color::RGB also has a by_hex static method, which will return a named Color::RGB object for the given hex code. The name method returns the name (if it has one):

    require "color"
    
    mystery_color = Color::RGB.by_hex("#ffefd5")
    puts mystery_color.name
    # => papayawhip
    

    You can see it in action on repl.it: https://repl.it/@jrunning/EqualReasonableSpellchecker (If you get an error the first time you hit the run button, hit it again. repl.it sometimes has trouble with loading gems the first time.)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search