While I agree with the existing answers (you should refactor to simply shuffle and return the first n cards), you can clean up your existing code dramatically by getting rid of all the temporary variables. The result is 5 slim lines of Ruby:
def deal(number_of_players, number_of_cards_each)
(1..number_of_cards_each).map do
begin
card = choose_card()
end while @current_dealt_card.include? card
@currently_dealt_cards << card
card
end
end
First thing, note the use of map
to do away with the players_card_array
stuff. Any time you see this very typical pattern....
def get_items
# make an empty array
items_to_return = []
# map some existing array to a set of new values
some_other_items.each do |item|
items.to_return << modify_item(item)
end
# return new values
return items_to_return
end
... you should be using map, and letting the result "fall off" the end of the method and be implicitly returned:
def get_items
some_other_items.map |item|
modoify_item(item)
end
end
Secondly, instead of initializing a watch variable (added_card = false
) and looping until it's set to true by some condition inside the loop, make the condition a condition of the loop:
added_card=false
while added_card==false
new_card = choose_card()
unless @currently_dealt_cards.include?(new_card)
players_cards_array << new_card
added_card= true
@currently_dealt_cards << new_card
end
end
becomes Ruby's equivalent of a do/while loop:
begin
card = choose_card()
end while @currently_dealt_cards.include? card
@currently_dealt_cards << new_card
You could further DRY up the above, by having @currently_dealt_cards
be a Set
, and then use:
begin
card = choose_card()
end until @currently_dealt_cards.add? card
number_of_players
parameter, returning cards for one player only. You should get your algorithm straight first. \$\endgroup\$deal
method? \$\endgroup\$