vendredi 1 mai 2015

Ruby - Delete number from random array and return array with n random numbers?

I want to make one method in ruby which returns one random number from an array and made this:

@nr = 1..60

def ar_one
    ar = @nr.to_a.shuffle
    ar.pop
end

But i get the numbers more than one time and the array is never nil. Whats wrong with this?

And I need a method which give me n*random_numbers_from_array. So if I say n=3 than than I want to have: [12, 1, 59] something like this and delete this 3 numbers at there index. I tried this but I only get one random number at index n-1 nothing more.

def ar_all(n=3)
    arr = []
    @nr.each do |nr|
        arr.insert(n-1,ar_one)
        n += -1
    return arr
end
end

Would be great if someone can say which mistake i made in arr_one and how to get all n random numbers in arr_all, Thanks.




Aucun commentaire:

Enregistrer un commentaire