Ruby 从数组中随机选择若干元素

sunjohn · October 14, 2012 · Last by canpig replied at October 23, 2012 · 7183 hits

array = [1, 2, 3, 4, 5] 中随机选择 n 个数,这 n 个数的结果要以数组给出。

写了个 method def select_random(array, n) array.shuffle.drop(array.size - n) end

觉得有点怪,麻烦各位给看下,有没有好的方法,谢谢啊!

array.shuffle[0...n]这样如何?

#2 楼 @5long 看来需要好好读读文档了,谢谢!

1-n 随即取数

现成的:array.sample(n)

You need to Sign in before reply, if you don't have an account, please Sign up first.