Ruby various loop output array elements

Source: Internet
Author: User


array = (1..10) .to_a
# method 1
length = array.length
length.times do | t |
  print "# {array [t]}"
end
puts "\ n"

# Method 2
length = array.length-1
for i in 0..length do
   print "# {array [i]}"
end
puts "\ n"

# Method 3
for i in array do
   print "# {i}"
end
puts "\ n"

# Method 4
array.each {| x | print x, ""}
puts "\ n"

# Method 5
length = array.length
i = 0
while i <length do
   print "# {array [i]}"
   i = i + 1
end
puts "\ n"

# Method 6
length = array.length
i = 0
until i == length do
   print "# {array [i]}"
   i + = 1
end
puts "\ n"

# Method 7
array.each_index do | i |
     print "# {array [i]}"
end
puts "\ n"

# Method 8
length = array.length-1
0.upto (length) do | i |
   print "# {array [i]}"
end
puts "\ n"

# Method 9
length = array.length-1
i = 0
loop do
   print "# {array [i]}"
   i + = 1
   break if i> length # You can also use break unless i <= length
end 


Ruby various loop output array elements


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.