ruby各种循环输出数组元素array = (1..10).to_a
# ⽅法1
length = array.length
length.times do |t|
print"#{array[t]} "
end
puts "\n"
# ⽅法2
length = array.length-1
for i in 0..length do
print"#{array[i]} "
ruby 字符串转数组
end
puts "\n"
# ⽅法3
for i in array do
print"#{i} "
end
puts "\n"
# ⽅法4
array.each{|x| print x,""}
puts "\n"
# ⽅法5
length = array.length
i = 0
while i< length do
print"#{array[i]} "
i = i+1
end
puts "\n"
# ⽅法6
length = array.length
i = 0
until i==length do
print"#{array[i]} "
i += 1
end
puts "\n"
# ⽅法7
array.each_index do |i|
print"#{array[i]} "
end
puts "\n"
# ⽅法8
length = array.length - 1
0.upto(length) do |i|
print"#{array[i]} "
end
puts "\n"
# ⽅法9
length = array.length - 1
i = 0
loop do
print"#{array[i]} "
i += 1
break if i > length #也可以⽤break unless i <= length
end
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论