until 循环是Ruby的强大功能,这使得它与其他编程语言不同的一个。对直到循环的支持指定了Ruby用户友好语言是多少?
until循环是while循环,如果我们在功能方面证明它正好相反。只要布尔条件为假,就执行while循环,但是直到until循环,只要布尔条件不为真,就执行while循环。这是进入控制循环的示例,其中在执行循环主体之前检查指定的条件。
使用以下语法可以实现until循环:
until conditional [do] # 要执行的代码 end
范例1:
=begin Ruby program to print a message 10 times using until loop =end num=0 until num==10 puts "Hello there! Message from nhooo.com! Happy learning!" num=num+1 end
输出结果
Hello there! Message from nhooo.com! Happy learning! Hello there! Message from nhooo.com! Happy learning! Hello there! Message from nhooo.com! Happy learning! Hello there! Message from nhooo.com! Happy learning! Hello there! Message from nhooo.com! Happy learning! Hello there! Message from nhooo.com! Happy learning! Hello there! Message from nhooo.com! Happy learning! Hello there! Message from nhooo.com! Happy learning! Hello there! Message from nhooo.com! Happy learning! Hello there! Message from nhooo.com! Happy learning!
范例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 #直到循环的实现 rem=num%10 num=num/10 sum=sum+rem end puts "The sum of #{temp} is #{sum}"
输出结果
Enter the number 456672 The sum of 456672 is 30
范例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 #直到循环的实现 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}"
输出结果
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