views:

96

answers:

3

What's the simplest way to get an array with three objects (Card), one of which I already have? The other two should be randomly selected from the database.

My current approach looks like this:

[
  @deck.cards[rand(@deck.cards.size)], 
  @deck.cards[rand(@deck.cards.size)],
  @mycard
].sort_by {rand}

The problem I have right now is that sometimes @mycard shows up twice in the array. How can this be avoided?

A: 

You have to remove each card from the deck as you draw from it, unless you are going to reshuffle after each draw, in which case I would just draw again until you get a unique one you haven't already drawn.

Robert Harvey
A: 

Get a card from the deck. Check it's not the samy as @mycard.

Get another card from the deck. Check it's not the same as @mycard or the previous card.

Pretty straightforward, I'd have thought.

Anon.
Yeah- I had thought perhaps there was a shorter way to do it that I had overlooked, but I guess not.
igul222
A: 

something like this might work:

class Card < ActiveRecord::Base
    belongs_to :deck

    named_scope :random, lambda {
        { :offset => Kernel.rand(Beer.count) }
    }

    named_scope :not_in, lambda { |a|
        { :conditions => [ 'id NOT IN (?)', a ] }
    }
end

my_cards = []
@mycard = Card.last
my_cards << @mycard
2.times {
    my_cards << @deck.cards.not_in(my_cards.collect(&:id)).random
}
Amiel Martin