How can I refactor the following code to avoid repetition?
r = @lots.fetch @lots.keys.sample
until (neighbours r)
r = @lots.fetch @lots.keys.sample
end
I basically have a new r object that is picked randomly and I need to pick r till the selected one doesn’t respond to certain criteria (neighbours r). How can I refactor it to avoid the repetition of getting r and keep getting it till a condition is reached? Thanks
Personally I would shuffle
@lots(turn it into a two element array if needed) and then use take_while like this:If you need the result as a hash again, just call
Hash[]on it:In your case the condition for take while would be something like
{ |k, v| !(neighbours v)}. Also if you want the elements from the starting hash to be repeatable, you’ll have to do use something else instead ofshuffle.