Search code examples
ruby-on-railsrubyshuffleplaying-cards

shuffle! an array n times in ruby


I am a semi-newbie to Ruby :*(, so thank you in advance. I'm learning as much as I can and I have searched for hours but can't seem to find the answer anywhere.

I have written this method in a Deck class.

def shuffle!
  @cards.shuffle!
end

I want to know if, using this method, I can modify it to shuffle the cards array 7 times instead of just once, which it currently does now. If not, do I have to write another method that calls .shuffle! and run that seven times once I initialize a new Deck. Thanks again for anyone that can help :)


Solution

  • You can do with some tricks as below,as Array#shuffle don't have such functionality,only n times. The doc is saying If rng is given, it will be used as the random number generator.

    def shuffle!(n=7)
      n.times { @cards.shuffle! }
    end
    

    If you call it a.shuffle only one time shuffling will be done on the array a.If you call as a.shuffle(random: Random.new(4)),then the shuffling time is random on array a.