gpt4 book ai didi

ruby - 如何生成六种随机的十六进制颜色并将它们放入 Ruby 数组中?

转载 作者:太空宇宙 更新时间:2023-11-03 17:17:29 32 4
gpt4 key购买 nike

我正在使用 RMagick 制作一个项目,该项目生成一个关于尺寸和颜色的随机横幅广告。

第一步是这样,但它不能正常工作。我正在使用所谓的三元语句来生成类似“#ffffff、#f0f1cd、#123fff”等的字符串。

# Generate sixteen random colors
1.upto(16) { |i|
(defined? colors) ? colors << ", #%06x" % (rand(0xffffff)) : colors = "#%06x" % (rand(0xffffff))
}
puts colors.split(',')

期望的结果不正确。我希望它分成一个数组,如: ["#ffffff", "#f0f1cd", "#123fff"]

以最优雅的方式。

最佳答案

你可以这样做,这样会更容易:

colors = 3.times.map{"%06x" % (rand * 0x1000000)}

注意:如果您使用的是 Ruby 1.9.3,则可以使用范围。

colors = 3.times.map{"%06x" % rand(0..0xffffff)}

关于ruby - 如何生成六种随机的十六进制颜色并将它们放入 Ruby 数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10677959/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com