2017-04-10 16 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" 
: 私は、色を選択して、ランダムに表示され、毎回異なる色が

私のコードを印刷しているされていることを希望します

もちろん、2つの同じ文字列が連続しているわけではありませんが、それでもあなたが探している文字列だと思います。

関連する問題