ruby - 如何在 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
每次我“击中”同一张牌时,我的问题是如何防止这种情况以及每次我们运行循环时返回“新”随机牌的方法。
谢谢。
解决方案
您将这个名称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
。
推荐阅读
- apache-poi - POI不复制ppt幻灯片笔记
- azure-container-service - 有没有办法像调度程序一样监控 AKS 控制平面进程?
- java - Pusher 在单次推送中复制并接收多个数据
- python - 多文件导入数据框给出错误
- java - 最短路径程序中的 NullPointerException
- linux - 超集、oracle 和 SQL Lab 没有属性 tzinfo_factory 的错误
- c++ - 您如何从嵌套类的方法中获取基类的“this”指针?
- javascript - 使用异步 js 遍历数组并在回调中执行函数以返回单个结果
- php - 邮件列表订阅
- sql - SQL Server:根据 SELECT TOP 100 Column 选择 TOP 10 Column