View Subcategory
Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)
Starting with a variable x=1, Print the sequence
"1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
ruby
x=1
while x < 150
puts x
x <<= 1
end
while x < 150
puts x
x <<= 1
end
Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)
Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be
"4,2,1,2,6"
ruby
# Ruby has no DO..WHILE construct. Need to write it as a WHILE
rnd = 0
while (rnd != 6)
rnd = rand(6)+1
print rnd
print "," if (rnd!=6)
end
rnd = 0
while (rnd != 6)
rnd = rand(6)+1
print rnd
print "," if (rnd!=6)
end
begin
rnd = rand(6)+1
print rnd
print "," if rnd!=6
end while rnd != 6
rnd = rand(6)+1
print rnd
print "," if rnd!=6
end while rnd != 6
# This uses Enumerators, ad it becomes almost functional style...
games = Enumerator.new do |yielder|
yielder.yield rand(6) + 1 while true
end
puts games.take_while {|roll| roll != 6}.join(",")
games = Enumerator.new do |yielder|
yielder.yield rand(6) + 1 while true
end
puts games.take_while {|roll| roll != 6}.join(",")
Perform an action a fixed number of times (FOR)
Display the string
"Hello" five times like "HelloHelloHelloHelloHello"
ruby
puts "Hello"*5
5.times { print "Hello" }
Perform an action a fixed number of times with a counter
Display the string
"10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
ruby
10.downto(1) { |n| print n, " .. " }
puts "Liftoff!"
puts "Liftoff!"
