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
add_prime(50)
print $arr.join(", "),"\n"
...全文
188 点赞 收藏 3
写回复
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
truebit 2011-01-06
看API文档是正途的说: http://www.rubydoc.info/stdlib/core/1.8.7/Numeric:step

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 }
从3开始每步加2直到小于等于N时,循环运行{}里的程序.num是每步算出来的数是[3,5,7,9...,n] 如果是素数就记到$arr数组里.
回复
saint1126 2010-07-08
num.step(limit, step ) {|i| block } => num


可以这样理解,这是一个循环,从数值num开始执行,步长为step,每执行一次,step*执行次数 + num 会与limit 进行比较,如果大于limit(step为正数时)结束,如果step负数时,小于limit结束.


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
创建于2007-09-28

2745

社区成员

Web 开发 Ruby/Rails
申请成为版主
社区公告
暂无公告