DEV Community

Discussion on: It's Ruby, There Must Be a Better Way

Collapse
 
tomlord profile image
Tom Lord • Edited

You could use Regexp#random_example in conjunction with the taken_names, as per your first solution in this blog post.

Or -- with the potential performance issue of storing a large array in ruby memory (as with all your other examples that use to_a!) -- you could also use Regexp#examples to end up with very similar solutions. (See the documentation.) For example:
.

@names = /[A-Z]{2}\d{3}/.examples(max_group_results: 26, max_results_limit: 676000).shuffle.each

...Note that this would be a bad idea if the pattern got longer, so the number of possible results was much larger. All of your examples that use to_a, just like my Regexp#examples code above, would soon freeze the system as the array length grows exponentially.

Using Regexp#random_example - similar to your original implementation - would scale fine though.