I am struggling to write a clean method which when passed an array of strings and x returns a randomised list of array elements totalling x, eg.
def getrandomarr开发者_运维问答ayelements(thearray, howmany)
return [something]
end
Yes I should submit my existing code, which whilst works is not good, it's 8 lines long and I have a feeling it can be done in one?!
In ruby 1.9:
irb(main):001:0> [1,2,3,4,5].sample(3)
=> [2, 4, 5]
irb(main):002:0> [1,2,3,4,5].sample(3)
=> [2, 5, 3]
and for ruby 1.8 something like this:
def sample(arr, n)
arr.shuffle[0...n]
end
irb(main):009:0> sample([1,2,3,4,5], 3)
=> [5, 1, 3]
irb(main):010:0> sample([1,2,3,4,5], 3)
=> [3, 4, 2]
精彩评论