In this code, I create an array of strings from "1" to "10000":
array_of_strings = (1..10000).collect {|i| String(i)}
Does the Ruby Core API provide a way to enumerate an object that allows me to enumerate the same list by generating string values on demand, rather than generating an array of strings?
Here is another example that hopefully clarifies what I'm trying to do:
def find_me_an_awesome_username awesome_names = (1..1000000).xform {|i| "hacker_" + String(i) } awesome_names.find {|n| not stackoverflow.userexists(n) } end
Where xform is the method I'm looking for. awesome_names is Enumerable, so xform does not create an array of strings of 1 million elements, but simply generates and returns strings of the form "hacker_ [N]" upon request.
By the way, here is how it looks in C #:
var awesomeNames = from i in Range(1, 1000000) select "hacker_" + i; var name = awesomeNames.First((n) => !stackoverflow.UserExists(n));
(one solution)
Here is an extension for Enumerator that adds an xform method. It returns another enumerator that iterates over the values of the original counter, with the conversion applied to it.
class Enumerator def xform(&block) Enumerator.new do |yielder| self.each do |val| yielder.yield block.call(val) end end end end
ruby enumerable
mackenir
source share