Reputation: 1478
For a pack of playing cards:
How can I use the suit hash (below) when creating a pack?
I have:
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
but I get:
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)
Upvotes: 0
Views: 220
Reputation: 20878
Here is a corrected version, check the comments :
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
Upvotes: 1
Reputation: 6485
You've actually put a hash in an array. To access the key, value pairs you'd have to access the array element first like this:
SUITS.first[:H]
Upvotes: 0
Reputation: 9049
Your Suit
definition and lookup don't look valid.
How about something like this (assuming the output is a pack of cards with all suit and numbers) -
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
Upvotes: 0
Reputation: 168091
Your Perhaps you wanted to do this:SUITS
is invalid expression.
SUITS = %w[Hearts Spades Diamonds Clubs]
And it is not clear what you are doing, but perhaps you should be doing this:
@cards =
SUITS.flat_map{|suit| CARDS.map{|number| PlayingCard.new(self, suit, number)}}
Upvotes: 2