stecd
stecd

Reputation: 1691

Ruby: rand method is not giving me a truly random number

I am trying to answer the following question from Chris Pine "Learn to Program" book:

• Write a Deaf Grandma program. Whatever you say to grandma (whatever you type in), she should respond with HUH?! SPEAK UP, SONNY!, unless you shout it (type in all capitals). If you shout, she can hear you (or at least she thinks so) and yells back, NO, NOT SINCE 1938! To make your program really believable, have grandma shout a different year each time; maybe any year at random between 1930 and 1950. (This part is optional, and would be much easier if you read the section on Ruby's random number generator at the end of the methods chapter.) You can't stop talking to grandma until you shout BYE. Hint: Don't forget about chomp! 'BYE'with an Enter is not the same as 'BYE' without one! Hint 2: Try to think about what parts of your program should happen over and over again. All of those should be in your while loop.

• Extend your Deaf Grandma program: What if grandma doesn't want you to leave? When you shout BYE, she could pretend not to hear you. Change your previous program so that you have to shout BYE three times in a row. Make sure to test your program: if you shout BYE three times, but not in a row, you should still be talking to grandma.

My code is giving me the same "random_year" when I run it. Why is the code not providing me an actual random year (between 1930 and 1950)?

Code in ruby.

# Deaf Grandma

random_year = 1930 + rand(1950 - 1930)

puts 'WHAT DO YOU WANT KID?'

bye = 0
talk_to_grandma = nil

while bye < 3 
  talk_to_grandma = gets.chomp
  if talk_to_grandma == "BYE"
    puts 'NO, NOT SINCE ' + random_year.to_s
    bye+=1
    elsif talk_to_grandma == talk_to_grandma.upcase
      puts 'NO, NOT SINCE ' + random_year.to_s 
      bye = 0
    else  
      puts "HUH?! SPEAK UP, SONNY!"
      bye = 0
  end
end

Upvotes: 0

Views: 610

Answers (3)

Horned
Horned

Reputation: 13

For that exercise I've used: rand(1930..1950)

Upvotes: 0

kostja
kostja

Reputation: 61538

You have assigned a value to the random_year variable in the first code line. It is selected randomly.

On each call to

puts 'NO, NOT SINCE ' + random_year.to_s 

the variable is accessed/read, but not modified.

You may want to encapsulate the random year generation in a method:

def random_year( start=1930, range = 20 )
  start + rand( range )
end

then you can use it like this:

puts "NO, NOT SINCE #{random_year}"

or, for a slightly older grandma:

puts "NO, NOT SINCE #{random_year(1910, 50)}"

Upvotes: 2

Marc B
Marc B

Reputation: 360632

You need to generate the random number inside your loop. Right now you generated it ONCE at the start of the program, and then it never changes. Basically:

while bye < 3 
    random_year = 1930 + rand(1950 - 1930)  // move the random generation to here
    puts 'NO, NOT SINCE ' + random_year.to_s

Upvotes: 4

Related Questions