ruby note——Loops and Iterators

1、For Loops

  ruby中for循环与c++等语言不太一样,c++中通常是条件表达式,确定start,达到end条件后结束for循环。而Ruby中for循环需要列举所有的items,然后一个一个去进行迭代.

eg: 

1 for i in [1,2,3]
2 
3     puts i 
4 
5 end

 

  另外each可以做同样的工作,称作“syntax sugar”。Arrays、Sets、Hashes、Strings集合都实现了each method.

eg:

1 [1,2,3].each do |x|
2 
3     puts x
4 
5 end

 

  both for and each can be used to iterate over the values in a range

eg:

 1 for i in 1..3
 2 
 3     puts i
 4 
 5 end
 6 
 7 (1..3).each do |s|
 8 
 9     puts s
10 
11 end

 

2、Mutiple Iterator Arguments

eg:

1 mutiarr = [["one","two","three","four"],[1,2,3,4]]
2  
3 for (a,b,c,d) in mutiaar
4     print "a=#{a},b=#{b},c=#{c},d=#{d}"
5 end

 

 3、While Loops

  

1 //when condition is true executes sleep
2 while tired
3     sleep
4 end
5 
6 //ececuted sleep precedes the test condition 
7 begin
8     sleep
9 end while tired

4、Until Loops //it can be thought of as a "while not" loop

1 i = 10
2 
3 puts(i) until i ==10 //never ececutes
4 
5 //once executes
6 bebin
7     puts(i)
8 end until i == 10

5、Loops

puts( "\nloop" )
 i=0 
loop do 
   puts(arr[i])
    i+=1 
    if (i == arr.length) then 
      break 
    end 
end 

 

posted on 2013-07-15 16:46  子墨sky  阅读(86)  评论(0)    收藏  举报

导航