tags:

views:

128

answers:

5

Hi,

I need a loop in this pattern. I need an infinite loop producing number that start with 1.

1,10,11,12..19,100,101,102..199,1000,1001.......
+2  A: 
INFINITY = 1.0 / 0.0
0.upto(INFINITY) do |i|
  ((10**i)...(2*10**i)).each{|e| puts e }
end

Of course, I wouldn't run this code.

Chubas
Looks neat. Of course I would break out of the loop :)
Bragboy
Wow, I didn't know that ruby could divide by 0.
DGM
@DGM: At least defined in the Float class, but not the Fixnum class. You could monkey-patch it to return Infinity too, but that'd probably break everything.
Chubas
+4  A: 
def numbers_that_start_with_1
  return enum_for(:numbers_that_start_with_1) unless block_given?

  infty = 1.0 / 0.0
  (0..infty).each do |i|
    (0 .. 10**i - 1).each do |j|
      yield(10**i + j)
    end
  end
end

numbers_that_start_with_1.first(20)
#=>  [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 100, 101, 102, 103, 104, 105, 106, 107, 108]
sepp2k
A: 

Enumerators are good for things like this. Though, I was lazy and just decided to see if the string representation starts with 1, and iterate through 1 at a time. This means it'll be slow, and it'll have huge pauses while it jumps from things like 1,999,999 to 10,000,000.

#!/usr/bin/env ruby

start_with_1 = Enumerator.new do|y|
  number = 1
  loop do
    while number.to_s[0] != '1'
      number += 1
    end

    y.yield number
    number += 1
  end
end

start_with_1.each do|n|
  puts n
end
AboutRuby
+1  A: 
i = 1
loop do
    for j in 0...i
        puts i+j
    end
    i *= 10
end
Nakilon
I like this answer for it's simplicity and clarity.
Cary Swoveland
A: 

Not better, just different...

def nbrs_starting_with_one(nbr=1)
   (nbr...2*nbr).each {|i| puts i}
   nbrs_starting_with_one(10*nbr)
end
Cary Swoveland
That will eventually throw a SystemStackError as you never return
glenn jackman
Glenn, you certainly are right, but it would take awhile, considering that the method performs 10^n "puts" the nth time it is called. I don't know how large "n" can become before the stack error occurs, but I'd hazard a guess that, for a typical Ruby implementation, my grandson would have grandchildren before the error occurred. Moreover, with no requirement to provide a means to end the operation, the question is rather hypothetical anyway.
Cary Swoveland