我如何找到两张纸牌的总和?

时间:2018-07-12 23:58:09

标签: arrays ruby sum

我无法正常工作,只是无法取出已发行的卡的值。

class Card
  attr_accessor :rank, :suit, :value

  def initialize (rank, suit, value)
    @rank = rank
    @suit = suit
    @value = value
  end

  def to_s
    "The #{rank} of #{suit} is #{value}"
  end
end

class Deck
  RANK_VALUE = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
  RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
  SUITS = ['Clubs', 'Diamonds', 'Spades', 'Hearts']

  def initialize
    @cards = []
    RANKS.each_with_index do |rank, index|
      value = RANK_VALUE[index]
        SUITS.each do |suit|
          @cards << Card.new(rank, suit, value)
        end
    end
  end

  def shuffle
    @cards.shuffle!
  end

  def deal
    @cards.pop(2) #how to sum the two cards here?
  end


end


deck = Deck.new
deck.shuffle
puts deck.deal

我应该将值放入数组中并求和吗?

1 个答案:

答案 0 :(得分:2)

一个简短而直接的解决方案:

a

如果您只是想将纸牌数组转换为值,显然可以省去总和,并且只需使用foo就可以得到一个值数组。

@cards.map(&:value).sum