until Loops

Ruby also has an until loop, which can be thought of as a while not loop. Its syntax and options are the same as those applying to while—that is, the test condition and the code to be executed can be placed on a single line (in which case the do keyword is obligatory) or can be placed on separate lines (in which case do is optional). There is also an until modifier that lets you put the code before the test condition and an option to enclose the code between begin and end in order to ensure that the code block is run at least once.

Here are some simple examples of until loops:

until.rb

i = 10

until i == 10 do puts(i) end     # never executes

until i == 10                    # never executes
    puts(i)
    i += 1
end

puts(i) until i == 10            # never executes

begin                            # executes once
    puts(i)
end until i == 10

Both while and until loops can, just like a for loop, be used to iterate over arrays and other collections. For example, the following code shows two ways of iterating over all the elements in an array:

array_iterate.rb

arr= [1,2,3,4,5]
i = 0

while i < arr.length
    puts(arr[i])
    i += 1
end

i=0
until i == arr.length
    puts(arr[i])
    i +=1
end
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.96