Monty Hall in Ruby

April 01, 2013

The Monty Hall Problem is one of the more weird statistical paradoxes. Yesterday, while trying to convicing my fiancée why changing your initial choice would give you better odds, I realized that writing a small Ruby Monte Carlo simulator of the problem might be a fun little challenge. How few lines of code would it take in Ruby, while still maintaining readability? I came up with the code below. If you can improve on it I’d love to hear!

def monty(switch)
  correct_answer, answer = rand(3), rand(3)
  open_door = ([0,1,2] - [answer,correct_answer]).first
  answer = ([0,1,2] - [answer,open_door]).first if switch
  answer == correct_answer

[true, false].each do |switch|
  wins = 0
  10_000.times { wins += 1 if monty(switch) }
  win_rate = (wins.to_f/10_000*100).round
  puts "#{switch ? "Not sticking" : "Sticking"} 
        with choice win rate: #{win_rate} %"
Share this post on Twitter
Morten Møller Riis

By Morten Møller Riis

I am a programmer, sysadmin, devops. I work for Gigahost in Copenhagen, Denmark. I am based in Odense, Denmark.

Twitter   ·   LinkedIn   ·   E-mail