0

对于一包扑克牌:

创建包时如何使用西装哈希(如下)?

我有:

class PackOfCards

  SUITS={H: 'Hearts', S:'Spades', D:'Diamonds', C:'Clubs'}
  CARDS=['A','2','3','4','5','6','7','8','9','10','J','Q','K']


  attr_accessor :pack_name, :cards

  def initialize(pack_name)

    @pack_name= pack_name
    @cards = []
    (0..3).each do |suit|
      (0..12).each do |number|
        @cards << PlayingCard.new(self, (SUITS[suit].value), CARDS[number])
      end 
    end 
  end 
end

class PlayingCard

  attr_accessor :pack, :card_number, :card_suit


  def initialize(pack, suit, number)
    @card_suit = suit
    @card_number = number
  end 

end

但我得到:

pack_of_cards.rb:16:in `block (2 levels) in initialize': 
undefined method `value' for 
{:H=>"Hearts", :S=>"Spades", :D=>"Diamonds", :C=>"Clubs"}:Hash (NoMethodError)
4

4 回答 4

2

SUITS的表达无效。也许你想这样做:

SUITS = %w[Hearts Spades Diamonds Clubs]

目前尚不清楚您在做什么,但也许您应该这样做:

@cards =
SUITS.flat_map{|suit| CARDS.map{|number| PlayingCard.new(self, suit, number)}}
于 2013-03-17T17:01:30.303 回答
1

这是一个更正的版本,请查看评论:

class PackOfCards
  SUITS={H: 'Hearts', S:'Spades', D:'Diamonds', C:'Clubs'} # Use curly braces to define a hash, [] braces will define an array containing one hash
  CARDS=['A','2','3','4','5','6','7','8','9','10','J','Q','K']
  attr_accessor :pack_name, :cards

  def initialize(pack_name)
    @pack_name= pack_name
    @cards = []
    SUITS.each_key do |suit| # each_key is better since it gives you the key of the hash
      (0..12).each do |number|
        puts PackOfCards::SUITS[suit]
        @cards << PlayingCard.new(self, (PackOfCards::SUITS[suit]), PackOfCards::CARDS[number]) # Call the hash with the right key to get the Suit
      end
    end
  end
end

class PlayingCard 
  attr_accessor :pack, :card_number, :card_suit

  def initialize(pack, suit, number)
    @card_suit = suit
    @card_number = number
  end

end
于 2013-03-17T17:04:32.240 回答
0

您的Suit定义和查找看起来无效。

像这样的东西怎么样(假设输出是一副带有所有花色和数字的卡片) -

class PackOfCards

  SUITS = ['Hearts', 'Spades', 'Diamonds', 'Clubs']
  CARDS=['A','2','3','4','5','6','7','8','9','10','J','Q','K']


  attr_accessor :pack_name, :cards

  def initialize(pack_name)

    @pack_name= pack_name
    @cards = []
    (0..3).each do |suit|
      (0..12).each do |number|
        @cards << PlayingCard.new(self, (SUITS[suit]), CARDS[number])
      end 
    end 
  end 
end

class PlayingCard

  attr_accessor :pack, :card_number, :card_suit


  def initialize(pack, suit, number)
    @card_suit = suit
    @card_number = number
  end 

end
于 2013-03-17T17:01:41.810 回答
0

您实际上已将哈希放入数组中。要访问键值对,您必须首先访问数组元素,如下所示:

SUITS.first[:H]
于 2013-03-17T17:03:15.273 回答