如何让ruby从数组中随机选取
我对编程相当陌生,我正在尝试做一个基本的石头剪刀程序 我已经用1=石头,2=布,3=剪刀制作了这个程序。但是现在我想试着用实际的单词而不是数字。如何让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
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
;否则就是平局。