# ruby 中3.step(n,2)？？？？何解？

zybbb 2010-07-08 08:56:35
\$arr=[ ] #建立一个全局数组 \$arr
\$arr[0]=2
def add_prime(n) #定义方法 将 n以内的奇素数加入\$arr
3.step(n,2){|num|\$arr <<num if is_prime?num }
end
def is_prime?(number) #定义方法 判断一个数是否是素数
j=0 #数组下标
while \$arr[j] * \$arr[j] <=number
return false if number % \$arr[j] ==0
j +=1
end
return true
end
print \$arr.join(", "),"\n"
...全文
197 点赞 收藏 3

3 条回复

truebit 2011-01-06

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

cocolong2002 2010-12-19
3.step(n,2){|num|\$arr <<num if is_prime?num }

saint1126 2010-07-08
``num.step(limit, step ) {|i| block } => num``

``````
def add_prime(n) #定义方法 将 n以内的奇素数加入\$arr
#这句话的含义时,由num以3开始,以2为步长递增,当num > n时候终止
3.step(n,2){|num|\$arr <<num if is_prime?num }

end
``````

``````
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.18128182845905

Ruby/Rails

2746

Web 开发 Ruby/Rails

2010-07-08 08:56