Home » Ruby programming

Ruby until loop with examples

until loop in Ruby: In this tutorial, we are going to learn about the until loop in Ruby programming with its syntax, examples.
Submitted by Hrithik Chandra Prasad, on July 31, 2019

The until loop

The until loop is one of the great features of Ruby which makes it different from other programming languages. The support of until loop specifies how much user-friendly language Ruby is?

The until loop is just the opposite of while loop if we justify it in terms of functionality. while loop is executed as long as the Boolean condition stands to be false but in case of until loop, it executes as long as the Boolean condition does not come out to be true. It is the example of the entry-control loop where the specified condition is checked prior to the execution of the loop's body.

The until loop is implemented with the help of the following syntax:

    until conditional [do]
        # code to be executed
    end

Example 1:

=begin 
Ruby program to print a message 10 times using until loop
=end

num=0

until num==10
    puts "Hello there! Message from Includehelp.com! Happy learning!"
    num=num+1
end

Output

Hello there! Message from Includehelp.com! Happy learning!
Hello there! Message from Includehelp.com! Happy learning!
Hello there! Message from Includehelp.com! Happy learning!
Hello there! Message from Includehelp.com! Happy learning!
Hello there! Message from Includehelp.com! Happy learning!
Hello there! Message from Includehelp.com! Happy learning!
Hello there! Message from Includehelp.com! Happy learning!
Hello there! Message from Includehelp.com! Happy learning!
Hello there! Message from Includehelp.com! Happy learning!
Hello there! Message from Includehelp.com! Happy learning!

Example 2:

=begin 
Ruby program to find the sum of all 
digits of given number using until loop
=end

puts "Enter the number"
num=gets.chomp.to_i

temp=num
sum = 0

until num==0
	#implementation of until loop
	rem=num%10
	num=num/10
	sum=sum+rem
end

puts "The sum of #{temp} is #{sum}"

Output

Enter the number
456672
The sum of 456672 is 30

Example 3:

=begin 
Ruby program to find the count of even 
and odd digits in the given number 
using until loop
=end

puts "Enter the number"
num=gets.chomp.to_i

temp=num
evecount=0
oddcount=0

until num==0
	#implementation of until loop
	rem=num%10
	num=num/10
	if rem%2==0
		puts "#{rem} is even"
		evecount+=1
	else
		puts "#{rem} is odd"
		oddcount+=1
	end
end

puts "Number of even numbers are #{evecount}"
puts "Number of odd numbers are #{oddcount}"

Output

Enter the number
7896532
2 is even
3 is odd
5 is odd
6 is even
9 is odd
8 is even
7 is odd
Number of even numbers are 3
Number of odd numbers are 4



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.