Ruby, Generate a random hex color

后端 未结 5 584
眼角桃花
眼角桃花 2020-12-23 02:09

How can I generate a random hex color with ruby?

5条回答
  •  鱼传尺愫
    2020-12-23 02:26

    also you can do this:

    colour = '#%X%X%X' % 3.times.map{ rand(255) }
    

    some updates:

    or if you want to freeze any color:

    class RandomColor
      def self.get_random
        rand(255)
      end
    
      def self.color_hex(options = {})
        default = { red: get_random, green: get_random, blue: get_random }
        options = default.merge(options)
        '#%X%X%X' % options.values
      end
    end
    

    then

    # full random colour
    
    RandomColor.color_hex() => #299D3D
    RandomColor.color_hex() => #C0E92D
    
    # freeze any colour
    
    RandomColor.color_hex(red: 100) => #644BD6
    RandomColor.color_hex(red: 100) => #6488D9
    

提交回复
热议问题