Reputation: 43
I am new to Ruby and am creating a Poker game application. I am trying to read in each player's cards from a text file. The data in the text file looks like this:
8C TS KC 9H 4S 7D 2S 5D 3S AC
5C AD 5D AC 9C 7C 5H 8D TD KS
3H 7H 6S KC JS QH TD JC 2D 8S
and so forth. The first 5 on each line are one player's cards, and the other 5 the other's. How would I go about reading in this data? I have already written a Card class that can create cards based on how they are represented in the file.
Upvotes: 2
Views: 60
Reputation: 198496
IO.foreach('cards.txt') do |line|
cards = line.chomp.split.map { |c| Card.new(c) }
hand1 = cards[0, 5]
hand2 = cards[5, 5]
#...
end
or...
handpairs = File.open('cards.txt') do |f|
f.each_line.map { |line|
line.chomp.split.each_slice(5).map { |cs|
cs.map { |c| Card.new(c) }
}
}
end
Upvotes: 2