James
James

Reputation: 5747

Passing Range#step multiple arguments

Ruby docs show that Range#step accepts one argument. It appears to be used for iterating over a range in increments of a number passed to step.

(0..100).step(5) { |x| puts x }

should produce:

0
5
10
15
...

In examples of the sieve of eratosthenes, people are passing Range#step what appears to be two arguments as seen here:

(primes[index] * 2).step(primes.last, primes[index]) do

What is going on here? What is happening when you pass step two arguments? When I test it with something like:

(0..100).step(5,10) { |x| puts x }

I get:

ArgumentError: wrong number of arguments (2 for 0..1)

Upvotes: 1

Views: 604

Answers (2)

Chuck
Chuck

Reputation: 237040

Multiplication doesn't return a Range, so that isn't Range#step -- it's Numeric#step, which takes an endpoint and a step amount.

Upvotes: 2

sawa
sawa

Reputation: 168101

Unlike what you claim that the method is Range#step, the one that you mentioned taking two arguments is Numeric#step. The first argument is the limit and the second argument is the step.

Upvotes: 1

Related Questions