Ruby哈希 - 如何在填充对象时使用哈希值?

时间:2013-03-17 16:52:59

标签: ruby hash ruby-1.9

对于一副扑克牌:

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

我有:

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 个答案:

答案 0 :(得分:2)

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

SUITS = %w[Hearts Spades Diamonds Clubs]

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

@cards =
SUITS.flat_map{|suit| CARDS.map{|number| PlayingCard.new(self, suit, number)}}

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分:0)

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

SUITS.first[:H]