ruby循环的实现形式

ruby语言的用法非常的灵活。
我们来举个简单的例子:如我们有个数组

array = %w[a b c d e f]

现在我们要遍历该数组,并打印出每个元素:
[
#方法一
length = array.list
length.times do |t|
 print "#{array[t]}"
end
/code]
#方法二
length = array.list-1
for i in 0..length do
  print "#{array[i]}"
end

#方法三
for i in array do
  print "#{i}"
end

#方法四
length = array.list
i = 0
while i< length do
  print "#{array[i]}"
  i = i+1
end

#方法五
length = array.list
i = 0
ubtil i==length do
  print "#{array[i]}"
  i += 1
end

#方法六
array.each do |i|
    print "#{i}"
end

#方法七
array.each_index do |i|
    print "#{array[i]}"
end

#方法八
length = array.list - 1
0.upto(length) do |i|#也可用downto:length.downto(0) do |i|
  print "#{array[i]}"
end

#方法九
length = array.list -1
i = 0
loop do
  print "#{array[i]}"
  i += 1
  break if i > length #也可以用break unless i <= length 
end

你可能感兴趣的:(C++,c,C#,Ruby,D语言)