打印

求教!!!

求教!!!

在找来的教材里遇到这个:
$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"    #转换成字符串输出

我对$arr[0]=2 3.step(n,2){|num|$arr <<num if is_prime?num } 

还有 def is_prime?(number) #定义方法 判断一个数是否是素
  j=0           #数组下标
  while $arr[j] * $arr[j] <=number
  return false if number % $arr[j] ==0
  j +=1
感觉不懂,因为教程前面没有这些个语法关键词的解释,忽然遇到这些感觉不理解
苦恼很久。。特来发帖求教

TOP

都已经有注释了,建议楼主,看下基础语法。语法关键字的解释,去下个API就可以了
给你个链接地址,http://www.roredu.com/download/RubyAPIWenDang.html
 下面是个step 方法的使用

num.step(limit, step ) {|i| block } => num


   1.step(10, 2) { |i| print i, " " }
   Math::E.step(Math:I, 0.2) { |f| print f, " " }

produces:

   1 3 5 7 9
   2.71828182845905 2.91828182845905 3.11828182845905


API解释:
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.

[ 本帖最后由 dong123qwe 于 2008-7-24 21:29 编辑 ]
create success (眼光,寂寞,做事) value(远,耐的住,黑暗);

TOP

2008-12-02 10:28 Crawled by CCBot/1.0 (+http://www.commoncrawl.org/bot.html) @38.103.63.61