Dick Davies
4/28/2005 9:19:00 PM
* Joe Van Dyk <joevandyk@gmail.com> [0417 22:17]:
> How can I neatly iterate from 0 to some number (either pos or neg)
> while skipping over some number of numbers?
>
> How's that for confusing?
>
> So,
>
> If the ending number is 550 and I want to skip by 100s, it would print
> 0, 100, 200, 300, 400, 500.
>
> If the ending number is -552 and I want to skip by 100s, it would print
> 0, -100, -200, -300, -400, -500
>
> There's nothing in the standard library that does this kind of thing, is there?
rasputnik$ ri Numeric#step
----------------------------------------------------------- Numeric#step
num.step(limit, step ) {|i| block } => num
------------------------------------------------------------------------
Invokes block with the sequence of numbers starting at num,
incremented by step on each call. The loop finishes when the value
to be passed to the block is greater than limit (if step is
positive) or less than limit (if step is negative). If all the
arguments are integers, the loop operates using an integer
counter. If any of the arguments are floating point numbers, all
are converted to floats, and the loop is executed floor(n +
n*epsilon)+ 1 times, where n = (limit - num)/step. Otherwise, the
loop starts at num, uses either the < or > operator to compare the
counter against limit, and increments itself using the + operator.
1.step(10, 2) { |i| print i, " " }
Math::E.step(Math::PI, 0.2) { |f| print f, " " }
produces:
1 3 5 7 9
2.71828182845905 2.91828182845905 3.11828182845905
rasputnik$
--
'Tempers are wearing thin. Let's hope some robot doesn't kill everybody.'
-- Bender
Rasputin :: Jack of All Trades - Master of Nuns