0

I am very new in Ruby and trying to have a randomly selected color from the array I have an array with 4 colors: Red, blue, white and pink I would like that a color has been selected and displayed randomly and everytime different color is printing

My code: (doesn't work)

@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 Answers1

1

Use sample method

@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" 

Obviously you can't be sure to not have two same strings in a row but still, I think this is what you're looking for.

Ursus
  • 29,643
  • 3
  • 33
  • 50