Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何让ruby从数组中随机选取_Ruby - Fatal编程技术网

如何让ruby从数组中随机选取

如何让ruby从数组中随机选取,ruby,Ruby,我对编程相当陌生,我正在尝试做一个基本的石头剪刀程序 我已经用1=石头,2=布,3=剪刀制作了这个程序。但是现在我想试着用实际的单词而不是数字。如何让ruby从我的数组中随机选择,我的 谢谢 mine = ["Rock", "Paper", "Scissors"] mine.sample(1 + rand(mine.count)) puts 'Write your choice, Rock, Paper, or Scissors' yours = gets.chomp.to_s if yours

我对编程相当陌生,我正在尝试做一个基本的石头剪刀程序

我已经用1=石头,2=布,3=剪刀制作了这个程序。但是现在我想试着用实际的单词而不是数字。如何让ruby从我的数组中随机选择,我的

谢谢

mine = ["Rock", "Paper", "Scissors"]
mine.sample(1 + rand(mine.count))
puts 'Write your choice, Rock, Paper, or Scissors'
yours = gets.chomp.to_s
if yours == "Rock"
    puts 'Your choice is Rock'


elsif yours == "Paper"
    puts 'Your choice is Paper'

else yours == "Scissors"
    puts 'Your choice is Scissors'

end
puts "--------------------------"
if mine == "Rock"
    puts 'Computer: My choice is Rock'


elsif mine == "Paper"
    puts 'Computer: My choice is Paper'

else mine == "Scissors"
    puts 'Computer: My choice is Scissors'

end


print 'Computer: My choice was: '
print mine
puts

if mine == "Rock" && yours == "Paper"
    puts "==========="
    puts "Paper Wins!"
    puts "==========="
elsif mine == "Paper" && yours == "Rock"
    puts "==========="
    puts "Paper Wins!"
    puts "==========="
elsif mine == "Paper" && yours == "Scissors"
    puts "=============="
    puts "Scissors Wins!"
    puts "=============="
elsif mine == "Scissors" && yours == "Paper"
    puts "=============="
    puts "Scissors Wins!"
    puts "=============="
elsif mine == "Scissors" && yours == "Rock"
    puts "=========="
    puts "Rock Wins!"
    puts "=========="
elsif  mine == "Rock" && yours == "Scissors"
    puts "=============="
    puts "Rock Wins!"
    puts "=============="
else
    puts "======================"
    puts "It's a tie! TRY AGAIN!"
    puts "======================"
end

您可以使用
示例

[1, 2, 3].sample #=> 1
[1, 2, 3].sample(2) #=> [3, 1]

考虑定义散列
winners={:rock=>:scissors,:scissors=>:paper,:paper=>:rock}
。假设玩家1和玩家2分别选择玩
c1
c2
。然后,如果玩家1赢了
赢家[c1]==c2
,玩家2赢了
赢家[c2]==c1
;否则就是平局。