def create_something(min_value)
loop do
something = SomeClass.generate_random
next unless something.some_attribute < min_value
return something
end
end
Refactorings
No refactoring yet !
Joel Williams
August 10, 2009, August 10, 2009 23:24, permalink
Can you change the generate_random method and pass in an (optional) maximum value? Is there a reason why you'd want to call the method a possibly infinite number of times?
def generate_random(max=>100) rand * max end generate_random(min_value)
bob
August 11, 2009, August 11, 2009 02:30, permalink
def create_something(min_value)
begin
something = SomeClass.generate_random
end while something.some_attribute < min_value
something
end
Alec Leitner
August 11, 2009, August 11, 2009 06:33, permalink
Joel, in my case that's not possible. As a brief explanation: I create ActiveRecord objects with random parameters, to then perform a complex calculation on them to decide if I want to save or discard them.
Bob: begin .. end while - that's an interesting syntax I havn't seen before!
Frahugo
August 14, 2009, August 14, 2009 13:04, permalink
You can simply use the until statement. Just make sure to test for nil value.
def create_something(min_value) something = SomeClass.generate_random until something && something.some_attribute < min_value end
Alec Leitner
August 15, 2009, August 15, 2009 23:36, permalink
Frahugo, that's a neat trick! Thanks a lot.
This is my version of looping a randomizer until a certain criteria is met. I could imagine that ruby has a smarter way of dealing with such loops.