Ruby, Generate a random hex color

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

How can I generate a random hex color with ruby?

5条回答
  •  悲&欢浪女
    2020-12-23 02:18

    You can generate each component independently:

    r = rand(255).to_s(16)
    g = rand(255).to_s(16)
    b = rand(255).to_s(16)
    
    r, g, b = [r, g, b].map { |s| if s.size == 1 then '0' + s else s end }
    
    color = r + g + b      # => e.g. "09f5ab"
    

提交回复
热议问题