class Urn def initialize(n_balls=2,black_proportion=0.5) @black = n_balls * black_proportion @white = n_balls * ( 1 - black_proportion ) end def draw_balls(n_draws=1) n_draws.times { prob_black = proportion rand < prob_black ? @black += 1 : @white += 1 # The statement above is equivalent to: # if rand < prob_black # @black += 1 # else # @while += 1 # end } end def proportion return @black.to_f / ( @black + @white ) end # n_balls = Number of balls initially in the urn # theta = Initial proportion of black balls # n_draws = Number of times to draw balls # precision = Number of test statistics to collect def Urn.sample(n_balls,theta,n_draws,precision=1000) draws = Array.new(precision) for i in 0...precision urn = Urn.new(n_balls,theta) urn.draw_balls(n_draws) draws[i] = urn.proportion end draws end end # The statement "__FILE__ == $0" is explained on page 337 of the pickaxe book. if __FILE__ == $0 theta = 0.5 draws = Urn.sample(10,theta,100,10_000) observed_test_statistic = 0.60 tail_count = 0 for i in 0...(draws.length) tail_count += ( draws[i] >= observed_test_statistic ? 1 : 0 ) end p_value = tail_count.to_f / draws.length puts "Ho: \\theta = #{theta}" puts "Test statistic is #{observed_test_statistic}" puts "p-value is #{p_value}" end