ruby各种循环的写法

ruby各种循环的写法

 

 

最常用的:

 

#1
length = array.list
length.times do |i|
 print "#{array[i]}"
end


#2
array.each do |value|
    print "#{value}"
end


#3
for vaule in array do
  print "#{value}"
end


#4
array.each_index do |i|
    print "#{array[i]}"
end
 
 

其他写法:

 

#5
length = array.list
i = 0
until i==length do
  print "#{array[i]}"
  i += 1
end


#6
length = array.list-1
for i in 0..length do
  print "#{array[i]}"
end


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


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


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

 

你可能感兴趣的:(Ruby)