第一次编程,我很困惑为什么我的ruby代码没有给出我想要的结果。我写了一个简单的程序来模拟滚动不同的多面骰子。
d4 = rand (1..4)
d6 = rand (1..6)
d8 = rand (1..8)
d12 = rand (1..12)
d20 = rand (1..20)
percent = rand (1..100)
puts "Which dice would you like to roll?"
which_dice = gets.chomp
puts "You rolled a #{which_dice}!"
前六行定义每个骰子以输出介于1和骰子边数之间的随机数。然后我要求用户输入他们想要使用gets方法滚动的骰子,然后将结果放在最后一行。
问题在于,当最后一行被执行时,它会输出"你滚动了一个(用户输入的get方法作为字符串)!"。例如,当用户在提示时输入d8时,它会输出"你滚动了一个d8!"而不是我想要的1到8之间的实际随机。我怎么能拥有它所以它放一个实际的随机数?
答案 0 :(得分:1)
您只是存储一个字符串然后打印它。你为什么期望这个字符串变成其中一个d-something? 无论如何,你可以做类似
的事情puts "Which dice would you like to roll?"
which_dice = gets.chomp.to_i
if [4, 6, 8, 12, 20, 100].include? which_dice
number = rand(1..which_dice)
puts "You rolled a #{number}!"
else
puts "This dice doesn't exist dude"
end
答案 1 :(得分:1)
您正在捕获其中_dice,不是变量名称的字符串值。解决这个问题的一种简单方法是将随机值放在哈希值中,然后使用字符串值按名称引用它们。
dice = {
"d4" => rand(1..4),
"d6" => rand(1..6),
"d8" => rand(1..8),
"d10" => rand(1..10),
"d12" => rand(1..12),
"d20" => rand(1..20)
}
puts "which dice would you like to roll?"
which_dice = gets.chomp
puts "You rolled a #{dice[which_dice]}"
您也可以使用它来更好地处理错误。
which_dice = dice[gets.chomp] || "non-existent die."
puts "You rolled a #{which_dice}"
如果他们试图滚动d7,将显示错误消息。
答案 2 :(得分:0)
使用当前脚本的相同结构获取输出的简短答案。
puts "You rolled a #{instance_eval(which_dice)}"
但是,有更好的方法可以通过使用不同的数据结构来实现这一目标。
答案 3 :(得分:0)
因此,快速而肮脏的响应是您当前仅从'gets.chomp'返回用户输入的文本。你对上面的变量一无所知。试试这个:
d4 = rand (1..4)
d6 = rand (1..6)
d8 = rand (1..8)
d12 = rand (1..12)
d20 = rand (1..20)
percent = rand (1..100)
puts "Which dice would you like to roll?"
which_dice = gets.chomp
case
when which_dice == 'd4'
amount = d4
when which_dice == 'd6'
amount = d6
when which_dice == 'd8'
amount = d8
when which_dice == 'd12'
amount = d12
when which_dice == 'd20'
amount = d20
when which_dice == 'percent'
amount = percent
end
puts "You rolled a #{amount}!"