2017-04-10 51 views
0
列表中随机输出

我非常新的Ruby和试图拥有从阵列 随机选择的颜色我有4种颜色数组:红色,蓝色,白色和粉红色 我想,一个色彩被选择和随机显示,每次不同的颜色印刷我怎么能有从字符串在Ruby中

我的代码:(不工作)

@colors =["blue", "orange", "red", "white"] 
    #random_color = colors[rand(0..(colors.length - 1))] 

    random_color = rand(0..(@colors.length - 1)) 
    print random_color 
    puts "Your choice: >" 
    guess = $stdin.gets.chomp 
    guesses = 0 


    while guess != random_color && guesses < 3 
    puts "Try again. You have to go out" 
    guesses += 1 
    print random_color 
    puts "Your choice: >" 
    guess = $stdin.gets.chomp 
    end 

回答

1

使用sample方法

@colors.sample 
=> "red" 
2.3.1 :011 > @colors.sample 
=> "white" 
2.3.1 :012 > @colors.sample 
=> "red" 
2.3.1 :013 > @colors.sample 
=> "white" 
2.3.1 :014 > @colors.sample 
=> "orange" 
2.3.1 :015 > @colors.sample 
=> "blue" 
2.3.1 :016 > @colors.sample 
=> "red" 

很明显,你不能确定连续有两个相同的字符串,但我认为这就是你要找的。