ruby comma operator and step question
Posted
by ryan_m
on Stack Overflow
See other posts from Stack Overflow
or by ryan_m
Published on 2010-03-09T10:06:26Z
Indexed on
2010/03/09
10:36 UTC
Read the original article
Hit count: 334
so, i'm trying to learn ruby by doing some project euler questions, and i've run into a couple things i can't explain, and the comma ?operator? is in the middle of both. i haven't been able to find good documentation for this, maybe i'm just not using the google as I should, but good ruby documentation seems a little sparse . . .
1: how do you describe how this is working? the first snippet is the ruby code i don't understand, the second is the code i wrote that does the same thing only after painstakingly tracing the first:
#what is this doing?
cur, nxt = nxt, cur + nxt
#this, apparently, but how to describe the above?
nxt = cur + nxt
cur = nxt - cur
2: in the following example, how do you describe what the line with 'step' is doing? from what i can gather, the step command works like (range).step(step_size), but this seems to be doing (starting_point).step(ending_point, step_size). Am i right with this assumption? where do i find good doc of this?
#/usr/share/doc/ruby1.9.1-examples/examples/sieve.rb
# sieve of Eratosthenes
max = Integer(ARGV.shift || 100)
sieve = []
for i in 2 .. max
sieve[i] = i
end
for i in 2 .. Math.sqrt(max)
next unless sieve[i]
(i*i).step(max, i) do |j|
sieve[j] = nil
end
end
puts sieve.compact.join(", ")
© Stack Overflow or respective owner