質問

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 :)

役に立ちましたか?

解決

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.

他のヒント

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.

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top