Ruby/Statement/while
Материал из Wiki.crossplatform.ru
(Различия между версиями)
Версия 17:10, 26 мая 2010
Another form you can use is with begin/end
temp = 98.3 begin print "Your temperature is " + temp.to_s + " Fahrenheit. " puts "I think you"re okay." temp += 0.1 end while temp < 98.6 puts "Your temperature is " + temp.to_s + " Fahrenheit. Are you okay?"
Here"s the formal specification for the while loop:
while condition [ do | : ] code end
loop code based on the result of a comparison made on each loop
x = 1 while x < 100 puts x x = x * 2 end
Replace one array with another
#!/usr/bin/env ruby i = 0 breeds = [ "quarter", "arabian", "appalosa", "paint" ] puts breeds.size # => 4 temp = [] while i < breeds.size do temp << breeds[i].capitalize i += 1 end temp.sort! # => ["Appalosa", "Arabian", "Paint", "Quarter"] breeds.replace( temp ) p breeds # => ["Appalosa", "Arabian", "Paint", "Quarter"]
The while Loop
i = 0 breeds = [ "q", "ar", "ap", "p" ] puts breeds.size # => 4 temp = [] while i < breeds.size do temp << breeds[i].capitalize i +=1 end temp.sort! breeds.replace( temp ) p breeds
The while loop executes its contained code while a condition that you specify remains true.
while($_ != "q") puts "Running..." print "Enter q to quit: " gets chomp end
use while loop to convert elements in an array to capitalized case
#!/usr/bin/env ruby i = 0 breeds = [ "quarter", "arabian", "appalosa", "paint" ] puts breeds.size # => 4 temp = [] while i < breeds.size do temp << breeds[i].capitalize i += 1 end temp.sort! # => ["Appalosa", "Arabian", "Paint", "Quarter"] breeds.replace( temp ) p breeds # => ["Appalosa", "Arabian", "Paint", "Quarter"]
While loop with array length
a = [1, "test", 2, 3, 4] i = 0 while (i < a.length) puts a[i].to_s + "X" i += 1 end