views:

109

answers:

2

[Rails] I need to run some code only 40% of the times, how may i do this?

i need to make some square items, and there can be a max of 5 per row, and a min of 1 per row. then i want to have a row with 2 boxes, 5boxe, 1 box and so on, random... the last box of the row, will have a clear:both class..

+2  A: 

Generate a random number between 0.0 and 1.0 for instance and check if it's less than or equal to 0.4.

Matti Virkkunen
Check should be "less than 0.4". The highest number returned, depending on the library, is usually 9.9.
Jennifer Zouak
It doesn't make any practical difference. Also without arguments, rand() return a number between 0 (inclusive) and 1 (exclusive).
Matti Virkkunen
Does <0.4 or <=0.4 really matter? 40 or 41%?
gbn
Why are you guys arguing over using decimals? `rand(10) < 4` is a random 40%
macek
+1  A: 

If you need to ensure that your task is run 4 out of 10 times then use this method:

some_task if run?

def run?()
 @i=(@i||0) + 1
 (@i-1)%10 < 4
end

Caveat:

You need to run the task at least 10 times to get the 40% distribution.
Distribution is not random

KandadaBoggu