我想在ruby中创建一个方法,它从数组中返回一个随机数,然后生成:
@nr = 1..60
def ar_one
ar = @nr.to_a.shuffle
ar.pop
end
但我得到的数字超过一次,数组永远不会是零。 这有什么不对吗?
我需要一个给我n * random_numbers_from_array的方法。 所以,如果我说n = 3比我想要的那样:[12,1,59]就像这样,并在那里删除这3个数字索引。 我尝试了这个,但我只得到索引n-1的一个随机数。
def ar_all(n=3)
arr = []
@nr.each do |nr|
arr.insert(n-1,ar_one)
n += -1
return arr
end
end
如果有人能说出我在arr_one中犯了哪个错误以及如何在arr_all中获取所有n个随机数,那将会很棒,谢谢。
答案 0 :(得分:3)
问题是,每次运行ar_one
方法时,实际上都会创建一个新数组。
ar = @nr.to_a.shuffle # <= here you create a new array and shuffle it
ar.pop # <= here you pop and return the first element of that new array
您的第二个示例失败,因为您在each
块的第一次迭代结束时从该方法返回,在收集后只有一个元素:
@nr.each do |nr|
arr.insert(n-1,ar_one)
n += -1
return arr #<= here you return from that method without checking `n`
end
我会做这样的事情:
class Sampler
def initialize(number = 60)
@array = (1..number).to_a.shuffle
end
def one
@array.pop
end
def many(number)
@array.pop(number)
end
end
sampler = Sampler.new(4)
sampler.one
#=> 2
sampler.many(3)
#=> [3, 1, 4]
答案 1 :(得分:0)
您可以通过简单易行的方式完成此任务:
@array = [1,2,3,4,5,6,7,8,9]
def random_collector
number = @array.sample
index = @array.index(number)
@array.delete_at(index)
number
end
答案 2 :(得分:0)
我建议:
@array
如果不修改'b'
,请操作副本。