Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More efficient way to create a list in Ruby

Tags:

for-loop

ruby

Just working with the 2-9 in a deck of cards.

What is the preferred and/or most efficient way to get the deck created in Ruby?

Is it what I have below, or how else can/should I do it?

deck = []
suits = ["spades", "diamonds", "clubs", "hearts"]

for x in suits
  for y in 2..9
    w = y.to_s
    deck.push(w+" of "+x)
  end
end
like image 989
CRABOLO Avatar asked Jan 30 '26 07:01

CRABOLO


2 Answers

I like product w/ a block

a, suits = [], ["spades", "diamonds", "clubs", "hearts"]
suits.product((2..9).to_a) {|t,n| a << "#{n} of #{t}"}
like image 172
Alex.Bullard Avatar answered Feb 02 '26 09:02

Alex.Bullard


suits = ["spades", "diamonds", "clubs", "hearts"]
deck = suits.product((2..9).to_a).map { |x,y| "#{y} of #{x}" }

If you want all 52 cards:

suits = ["spades", "diamonds", "clubs", "hearts"]
faces = { 1 => 'Ace', 11 => 'Jack', 12 => 'Queen', 13 => 'King' }
deck = suits.product((1..13).to_a).map { |x,y| "#{faces[y]||y} of #{x}" }
# => Ace of spades, 2 of spades, ..., King of spades, Ace of diamonds, etc.
like image 31
Matt Avatar answered Feb 02 '26 11:02

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!