Reputation: 119
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 :)
Upvotes: 1
Views: 1010
Reputation:
You'd probably want to do something along these lines.
class Deck
def initialize(cards)
@cards = cards
end
def shuffle!(n = 7)
n.times { @cards.shuffle! }
@cards
end
end
cards = [1, 2, 3, 4]
Deck.new(cards).shuffle! # => [3, 4, 1, 2]
Note that the method will return the value of @cards.
Upvotes: 1
Reputation: 118271
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
.
Upvotes: 3
Reputation: 11007
If you're always going to shuffle the deck 7 times, I think you don't need to pass an argument - try this:
def shuffle
7.times {self.shuffle!}
end
and in initialize
def initialize
#your code here
@cards.shuffle
end
Upvotes: 0