调用哈希值时,如何将变量设置为键?

时间:2019-05-11 20:32:14

标签: ruby

当用户输入“命中”时,会为他们分配一个随机卡。我已经将卡设置为键,并将点设置为哈希值,并且每次尝试调用它时,卡都不会放置任何东西!

def random_card
  cards = ["two", "three", "four", "five", "six", "seven",
           "eight", "nine", "ten",
           "jack", "queen", "king", "ace"]

  cards[rand(13)]
end

def score
  card_value = {
  two: 2,
  three: 3,
  four: 4,
  five: 5,
  six: 6,
  seven: 7,
  eight: 8,
  nine: 9,
  ten: 10,
  jack: 10,
  queen: 10,
  king: 10,
  ace: 11,
}
puts "point #{card_value[:card]}"
end

def move
  while true
    puts '"hit" or "stick"'
    input = gets.chomp
    if input == "hit"
      puts card = random_card
      score
    end
    break if input == "stick"
  end
end

当用户输入“命中”时,输出应该是随机卡片,并且该点将分配给该卡片,例如,三分3

3 个答案:

答案 0 :(得分:2)

最简单的就是更新

puts "point #{card_value[:card]}"

收件人

puts "point #{card_value[random_card.to_sym]}"

原因是card_value[:card]试图从他们的card_value哈希中获取他们的卡密钥,该密钥不存在。

您的random_card函数从其主体中定义的cards数组返回一个“随机”字符串值,它是一个字符串,您将得到相同的错误,因为card_value中的键是符号,因此您需要将该结果转换为符号。



正在回答dx7不错的补充。

您只需声明一个CARD_VALUES散列,其中包含卡的名称和点,然后您可以使用Array#sample进行提取,因此避免为卡添加无用的实例变量,而不必将其作为方法传递调用random_card时的参数:

CARD_VALUES = { two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10,
               jack: 10, queen: 10, king: 10, ace: 11 }

def random_card
  CARD_VALUES.to_a.sample
end

def move
  loop do
    puts '"hit" or "stick"'
    input = gets.chomp
    if input == 'hit'
      card, point = random_card
      puts "card: #{card}"
      puts "point: #{point}"
    end
    break if input == 'stick'
  end
end

move

答案 1 :(得分:0)

您还可以为所有卡片定义一个常数,使用键构建一个牌组,然后对牌组进行洗牌,然后弹出卡牌:这样可以避免两次获得卡片。

CARDS = {two: 2,three: 3,four: 4,five: 5,six: 6,seven: 7,eight: 8,nine: 9,ten: 10,jack: 10,queen: 10,king: 10,ace: 11}

deck = CARDS.keys # it's an array with all the keys
# score = 0 # just in case
loop do
  puts '"hit" or "stick"'
  input = gets.chomp
  if input == "hit"
    puts card = deck.shuffle!.pop # so you are removing the card from the deck
    puts value = CARDS[card]
    # puts score += value # just in case
  end
  break if input == "stick"
end
# puts score # just in case

答案 2 :(得分:-1)

我将尝试不改变您的算法就回答您。

问题是{ ... }。您在散列puts "point #{card_value[:card]}"上没有那个:card键。考虑到您想从先前获得的随机卡中获得分数,您需要将该卡传递给计分方法,然后获得分数。

card_value

您的卡是字符串,您的哈希def random_card cards = ["two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace"] cards[rand(13)] end def score(card) card_value = { two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, jack: 10, queen: 10, king: 10, ace: 11, } puts "point #{card_value[card.to_sym]}" end def move while true puts '"hit" or "stick"' input = gets.chomp if input == "hit" puts card = random_card score(card) end break if input == "stick" end end move 使用符号作为键。因此,您需要使用card_value将字符串转换为符号。