首页 > 解决方案 > 如何在 Ruby (v2.6.3) 中获取随机数

问题描述

我正在做一个任务,我必须制作一个简单的纸牌游戏。导师为我提供了一种生成随机卡片的方法 - 我不允许更改:

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

  cards[rand(13)]
end

并且我尝试了一种方法,可以将牌添加到玩家手中,random_card每次都调用该方法:

def move(random_card)
  player_hand = []
  while true do
    puts "Make a move. Enter 'hit' or 'stick' "
    choice = gets.chomp
    if choice == "stick"
      break
    elsif choice == "hit"
      # this is currently giving me the same card for each "hit"
      # but a different one each time I run the code.
      player_hand.push(random_card)
    end
  end
  # TODO change this to return
  puts player_hand
end

每次我“击中”同一张牌时,我的问题是如何防止这种情况以及每次我们运行循环时返回“新”随机牌的方法。

谢谢。

标签: rubyrandomrandom-seed

解决方案


您将这个名称random_card用于两件不同的事情:1)您的导师给您的方法;和 2)move方法的参数名称。

第二种用法定义了一个局部变量,它掩盖(或隐藏)方法名称。换句话说,move方法内random_card指的是您在调用时传入的任何值move。它不调用该方法。

这是一个简单的例子:

def foo
  %w(hi hey howdy)[rand 3]
end

def bar1
  puts foo
end

def bar2(foo)
  puts foo
end

5.times { bar1 }  # produces a random selection of hi's, hey's, and howdy's
puts
5.times { bar2 "Help!  I'm stuck!" }  # prints the passed message 5 times
puts
5.times { srand 12345; bar1 }  # produces "howdy" 5 times

鉴于您所展示的内容,您可能不需要对move. 如果你这样做,给它自己的名字。还要确保你没有弄乱srand程序中的其他地方。


另一种选择是通过使用括号来指示您要使用方法而不是具有相同名称的参数。使用上面的示例,更改bar2为:

def bar2(foo)
  puts foo()
end

空括号清楚地表明这是对方法的调用foo,而不是对(现在未使用的)参数的引用foo


推荐阅读