Just add the two halves back together:
$deck = bottomcut + topcut
In Ruby, adding arrays is equivalent to concatenating their elements:
irb(main):001:0> [1, 2, 3] + [3, 4, 5]
=> [1, 2, 3, 3, 4, 5]
Вопрос
I'm trying to simulate a deck of cards being cut. So I prompt the player to pick a number between 1 and 32(the number of cards in this deck). That is stored in the $cut_the_deck_number
variable.
Then I need to somehow move the cards (from that number to the end of the deck), to the front of the deck.
This code somewhat works, however not good, b.c it creates a 2D array, when I just need a list.
I need $deck to be
$deck = ["2 of diamonds", "5 of clubs", etc]
instead of
$deck = [["2 of diamonds, "5 of clubs"], ["8 of spades", etc, etc]]
I know there is some other method, but it wouldn't work because I'm using RUBY 1.8.7
def cuttingthedeck
bottomcut = $deck.pop($cut_the_deck_number)
topcut = $deck.pop($deck.length)
$deck.push(bottomcut)
$deck.push(topcut)
end
Решение
Just add the two halves back together:
$deck = bottomcut + topcut
In Ruby, adding arrays is equivalent to concatenating their elements:
irb(main):001:0> [1, 2, 3] + [3, 4, 5]
=> [1, 2, 3, 3, 4, 5]
Другие советы
You could flatten your array: $deck.flatten!
. This is an alternative:
deck = ["a", "b", "c", "d", "e"]
cut = 2
deck += deck.slice!(0, cut)
p deck #=> ["c", "d", "e", "a", "b"]
Personally, I'd use classes to represent the deck and the cards…
Cards might be:
class Card
attr_reader :suit, :value
def initialize(suit, value)
@suit, @value = suit, value
end
def to_s
value = case @value
when 1
:A
when 11
:J
when 12
:Q
when 13
:K
else
@value
end
"#{value}#{suit}"
end
alias_method :inspect, :to_s
end
And Deck could look like:
class Deck
attr_reader :cards
def initialize
@cards = []
[:S, :H, :D, :C].each do |suit|
([1] + (7..13).to_a).each do |value|
@cards << Card.new(suit, value)
end
end
end
def shuffle!
@cards.shuffle!
self
end
def cut!(cut_at = nil)
cut_at ||= rand(1..(@cards.size - 1))
@cards += @cards.slice!(0, cut_at)
self
end
end
You could then call:
require 'pp'
pp Deck.new.shuffle!.cut!