【问题标题】:How to generate six random hex colors and put them in a Ruby array?如何生成六种随机十六进制颜色并将它们放入 Ruby 数组中?
【发布时间】:2012-05-27 12:33:19
【问题描述】:

我正在使用 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"]

尽可能采用最优雅的方法。

【问题讨论】:

    标签: ruby colors hex rmagick


    【解决方案1】:

    你可以这样做会更容易:

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

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

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

    【讨论】:

    • +1 加上一点点 - 这样#ffffff 将永远不会产生。 rand 在 [0;1[ 范围内(参见Kernel#rand),即不包括 1。
    • @emboss 谢谢,你是对的。我已经编辑包括#ffffff
    • 我会的,但我没有问这个问题:)
    • 嘿嘿嘿嘿对不起,我的错 :)...我才意识到,对不起嘿嘿
    猜你喜欢
    • 2011-12-29
    • 1970-01-01
    • 2015-10-07
    • 2016-02-04
    • 2012-12-09
    • 2014-07-03
    • 2018-08-26
    相关资源
    最近更新 更多