Search code examples
rubyarrayslistruby-1.8.7

Re-arranging a 1d list in Ruby


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

Solution

  • 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]