从散列中选择随机键和值对

时间:2015-07-18 13:23:48

标签: ruby

我一直在尝试从哈希中选择随机密钥和值对。就我而言,这是一副纸牌。我一直在尝试,但没有得到正确的答案

这是我到目前为止的代码

deck = {
    "hearts" => [2,3,4,5,6,7,8,9,10,"jack","queen","king","ace"],
    "diamonds" => [2,3,4,5,6,7,8,9,10,"jack","queen","king","ace"],
    "spades" => [2,3,4,5,6,7,8,9,10,"jack","queen","king","ace"],
    "clubs" => [2,3,4,5,6,7,8,9,10,"jack","queen","king","ace"]
}

def create_deck(deck)
  hand = deck[deck.keys.sample]
  puts hand
  hand
end

2 个答案:

答案 0 :(得分:0)

如果要重新设置键和值对,请将其更改为:

def create_deck(deck)
  key = deck.keys.sample
  {key: deck[key]}
end 

答案 1 :(得分:0)

我会做这样的事情:

def create_deck(deck)
  cards = deck.keys.sample
  deck.each {|key, value| cards = [key, value] if cards == key}
end
# => ["clubs", [2, 3, 4, 5, 6, 7, 8, 9, 10, "jack", "queen", "king", "ace"]]

那应该返回一个 [key,value] 数组。