使用Ruby中的循环初始化数组

时间:2014-01-28 19:26:00

标签: ruby

我是从Java来的Ruby,第二天对它不太满意。我正在做的是用给定数量的套牌初始化卡片组。假设我将使用2副牌,每张牌中有52张牌,因此总共有104张牌(不使用Jokers)。我的计划是:

def initialize(num)
    @num_of_decks = num
    # initialize my cards here...
end

初始化后,我希望我的卡片是:

cards = {"Diamond A", "Diamond 2", ... "Diamond K", 
         "Club A", ...
         ...
         "Spade A", ... "Spade K", // end of the first deck
         "Diamond A", ...
         ...
         "Spade A", ... "Spade K" // end of the second deck
        }

我希望我的程序能够适应num_of_decks的任何内容。我现在并不清楚Ruby循环是如何工作的,特别是在Ruby中似乎不鼓励使用for循环时。希望任何人都可以在这里提供一个例子,以便我可以研究它是如何工作的。

4 个答案:

答案 0 :(得分:4)

faces = %w( A 2 3 4 5 6 7 8 9 10 J Q K )
suits = %w( Diamond Club Heart Spade )
deck = suits.product(faces).map { |p| p.join ' ' }

def initialize(num)
  @num_of_decks = num
  cards = deck * num
end

答案 1 :(得分:3)

嗯,我不完全确定你在问什么,但也许这样的事情会起作用?

class DrawPile
  CARD_SUITS = ["Diamond", "Heart", "Spade", "Club"]
  CARD_FACES = ["A", *(2..10).map(&:to_s), "J", "Q", "K"]
  A_DECK = CARD_SUITS.product(CARD_FACES).map{|x| x.join " "}
  def initialize(num)
    @num_of_decks = num
    @cards = (A_DECK * num).shuffle
  end

  attr_reader :num_of_decks, :cards
end

用法:

pile = DrawPile.new(2)
pile.num_of_decks #=> 2
pile.cards #=> ["Spade 2", "Spade K", "Heart 4", "Heart 7", ...]

答案 2 :(得分:0)

您可以使用:

a = ['Spade', 'Diamond', 'Club', 'Heart']
b = ['A', *('2'..'10'), 'J', 'Q', 'K']
cards = a.product(b).collect { |a| a.join(' ') }
total_cards = [*(cards * num_of_decks)]
# => ["Spade A", "Spade 2", "Spade 3", "Spade 4", ..., "Diamond A", "Diamond 2", "Diamond 3", ..., "Spade A", "Spade 2", "Spade 3", "Spade 4", ...]

here就是你可以玩的地方。

答案 3 :(得分:0)

suits = ['spades', 'diamonds', 'clubs', 'hearts']
values = ['Ace', '2', '3', '4', 'Jack', 'Queen']
cards = suits.product(values).map{|suit, value| "#{value} of #{suit}"}

p cards #=> ["Ace of spades", "2 of spades", "3 of spades", "4 of spades", "Jack of spades"