72820eaf703cd07ba9bc6ecc09e5d81a

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.

1
2
3
4
5
6
7
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 !

Avatar

Joel Williams

August 10, 2009, August 10, 2009 23:24, permalink

No rating. Login to rate!

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?

1
2
3
4
5
def generate_random(max=>100)
  rand * max
end

generate_random(min_value)
Avatar

bob

August 11, 2009, August 11, 2009 02:30, permalink

1 rating. Login to rate!
1
2
3
4
5
6
def create_something(min_value)
  begin
    something = SomeClass.generate_random
  end while something.some_attribute < min_value
  something
end
72820eaf703cd07ba9bc6ecc09e5d81a

Alec Leitner

August 11, 2009, August 11, 2009 06:33, permalink

No rating. Login to rate!

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!

B51ddb971f0e250f1cd68781f31b739b

Frahugo

August 14, 2009, August 14, 2009 13:04, permalink

1 rating. Login to rate!

You can simply use the until statement. Just make sure to test for nil value.

1
2
3
def create_something(min_value)
  something = SomeClass.generate_random until something && something.some_attribute < min_value
end
72820eaf703cd07ba9bc6ecc09e5d81a

Alec Leitner

August 15, 2009, August 15, 2009 23:36, permalink

No rating. Login to rate!

Frahugo, that's a neat trick! Thanks a lot.

Your refactoring





Format Copy from initial code

or Cancel