Pau*_*fer 549 ruby arrays random
我想知道是否有更清洁的方法来做到这一点.基本上,我想从可变长度的数组中选择一个随机元素.通常情况下,我会这样做:
myArray = ["stuff", "widget", "ruby", "goodies", "java", "emerald", "etc" ]
item = myArray[rand(myarray.length)]
Run Code Online (Sandbox Code Playgroud)
更换第二行是否有更易读/更简单的东西?或者这是最好的方法.我想你可以这样做myArray.shuffle.first,但我#shuffle几分钟前才看到SO,我还没有真正用过它.
Mar*_*une 1097
只需使用Array#sample:
[:foo, :bar].sample # => :foo, or :bar :-)
Run Code Online (Sandbox Code Playgroud)
它在Ruby 1.9.1+中可用.为了能够在早期版本的Ruby中使用它,你可以 require "backports/1.9.1/array/sample".
请注意,在Ruby 1.8.7中,它存在于不幸的名称之下choice; 它在更高版本中重命名,因此您不应该使用它.
虽然在这种情况下sample没用,但如果您需要多个不同的样本,则接受一个数字参数.
bee*_*soh 81
myArray.sample(x) 还可以帮助您从数组中获取x个随机元素.
小智 13
myArray.sample
Run Code Online (Sandbox Code Playgroud)
将返回1个随机值.
myArray.shuffle.first
Run Code Online (Sandbox Code Playgroud)
也将返回1个随机值.
Mik*_*das 12
def random_items(array)
array.sample(1 + rand(array.count))
end
Run Code Online (Sandbox Code Playgroud)
my_array = ["one", "two", "three"]
my_array.sample(1 + rand(my_array.count))
=> ["two", "three"]
=> ["one", "three", "two"]
=> ["two"]
Run Code Online (Sandbox Code Playgroud)
以下是我对此处发布的一些答案进行的一些基准测试,使用的速度sample始终比其他测试快。
test_arr = ["stuff", "widget", "ruby", "goodies", "java", "emerald" ]\n\nBenchmark.ips do |x|\n x.report("1 - sample") { test_arr.sample }\n x.report("2 - shuffle") { test_arr.shuffle.first }\n x.report("3 - length") { rand(test_arr.length) }\n x.report("4 - rand rand") { test_arr.sample(1 + rand(test_arr.count)) }\n x.report("5 - rand el") { test_arr[rand(test_arr.count)]}\n x.report("6 - switch") { \n case rand(0..test_arr.length) \n when 0\n test_arr[0]\n when 1\n test_arr[1]\n when 2\n test_arr[2]\n when 3\n test_arr[3]\n when 4\n test_arr[4]\n when 5\n test_arr[5]\n end \n } \n\n x.compare!\nRun Code Online (Sandbox Code Playgroud)\n测试在 MacBook Pro(15 英寸,2018 年)、2.6 GHz 6 核 Intel Core i7、32 GB 2400 MHz DDR4 上运行
\nWarming up --------------------------------------\n 1 - sample 713.455k i/100ms\n 2 - shuffle 253.848k i/100ms\n 3 - length 489.078k i/100ms\n 4 - rand rand 236.396k i/100ms\n 5 - rand el 447.244k i/100ms\n 6 - switch 419.272k i/100ms\nCalculating -------------------------------------\n 1 - sample 7.505M (\xc2\xb1 3.2%) i/s - 37.813M in 5.044078s\n 2 - shuffle 2.661M (\xc2\xb1 2.1%) i/s - 13.454M in 5.057659s\n 3 - length 5.021M (\xc2\xb1 1.6%) i/s - 25.432M in 5.066159s\n 4 - rand rand 2.352M (\xc2\xb1 2.4%) i/s - 11.820M in 5.029415s\n 5 - rand el 4.452M (\xc2\xb1 2.2%) i/s - 22.362M in 5.025623s\n 6 - switch 4.324M (\xc2\xb1 1.1%) i/s - 21.802M in 5.043294s\n\nComparison:\n 1 - sample: 7504636.7 i/s\n 3 - length: 5021326.6 i/s - 1.49x (\xc2\xb1 0.00) slower\n 5 - rand el: 4452078.6 i/s - 1.69x (\xc2\xb1 0.00) slower\n 6 - switch: 4323511.6 i/s - 1.74x (\xc2\xb1 0.00) slower\n 2 - shuffle: 2661267.7 i/s - 2.82x (\xc2\xb1 0.00) slower\n 4 - rand rand: 2351630.7 i/s - 3.19x (\xc2\xb1 0.00) slower\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
247871 次 |
| 最近记录: |