generate a random boolean in ruby

One way to generate a random boolean in Ruby is to use the rand method to return a random float between 0 and 1, and then compare it to a threshold value.

main.rb
# generate random boolean with probability p of being true
def random_boolean(p=0.5)
  rand < p
end
100 chars
5 lines

This function takes an optional probability p (defaulting to 0.5), and returns true with probability p, and false with probability 1 - p.

Here's an example usage:

main.rb
# generate 10 random booleans with probability 0.8 of being true
10.times do
  puts random_boolean(0.8)
end
108 chars
5 lines

This will output something like:

main.rb
true
false
true
true
true
true
false
true
true
true
52 chars
11 lines

gistlibby LogSnag