1

i just began learning ruby. now im trying to code a little script which plays the montyhall problem i got a problem with the last line of the code

numgames = 10000 # Number of games to play 
switch = true # Switch your guess?
wins = 0
numgames.times do doors = [0, 0, 0] # Three doors! 
doors[rand(3)] = 1 # One of them has a car! 
guess = doors.delete_at(rand(3)) # We pick one of them!
doors.delete_at(doors[0] == 0 ? 0 : 1) # Take out one of the remaining doors that is not a car! 
wins += switch ? doors[0] : guess end
puts "You decided #{switch ? "" : "not "}to switch, and your win % is #{wins.times ()/numgames}"

3 Answers 3

2

In the last line replace

wins.times ()

with

wins

times returns Enumerator, which doesn't play well with division.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! But im still getting a syntax error. monty.rb:9: syntax error, unexpected ')' ...nd your win % is #{wins.size ()/numgames}"
Are your parentheses balanced?
Does that mean that every parantheses is correctly opened and closed? Then yes!
wins is an integer. Why call times or size on an integer?
1

Two problems:

First, wins and numgames are integers, and integer division returns an integer:

irb(main):001:0> 6632 / 10000
=> 0

So, change wins = 0 to wins = 0.0. This will force a floating point division, which will return a floating point answer.

Second, wins is a number, not an array. So get rid of wins.times() and wins.size(). Both are wrong.

With these two changes in place, I consistently get around 66% wins, which just goes to show that Marilyn vos Savant is way smarter than I am.

Comments

0

Your wins is an integer so you don't need .times or .size, you do, however, want .to_f to force things into floating point mode:

wins.to_f / numgames

And if you want a percentage, then you'll have to multiply by 100:

wins.to_f / numgames * 100

You should also properly indent your code for readability and break things up with line breaks to make it easier to read and easier for the parser to figure out:

numgames = 10000 # Number of games to play
switch = true # Switch your guess?
wins = 0
numgames.times do
    doors = [0, 0, 0] # Three doors!
    doors[rand(3)] = 1 # One of them has a car!
    guess = doors.delete_at(rand(3)) # We pick one of them!
    doors.delete_at(doors[0] == 0 ? 0 : 1) # Take out one of the remaining doors that is not a car!
    wins += switch ? doors[0] : guess
end
puts "You decided #{switch ? "" : "not "}to switch, and your win % is #{100 * wins.to_f / numgames}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.