Ruby: for, while, Loop Examples

By Xah Lee. Date:

“for” Loop

#-*- coding: utf-8 -*-
# ruby

aa = 1..9 # creates a array 1 to 9
for xx in aa do
  p xx
end # prints 1 to 9

“while” Loop

#-*- coding: utf-8 -*-
# ruby

x = 1;
while x <= 9 do
  p x
  x += 1
end

Exiting Loop

#-*- coding: utf-8 -*-
# ruby

for xx in 1..9 do
  p xx
  if xx == 4 then break end
end # prints 1 to 4

If you have a question, put $5 at patreon and message me.

  1. Ruby Basics
  2. Doc Lookup
  3. Print Version String
  4. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?

  1. Unicode 💎
  2. Quote String
  3. Quote Long String
  4. Format String
  5. String Operations
  6. True, False
  7. “if then else”
  8. for, while, Loop
  9. List
  10. Loop Thru List
  11. Hash Table
  12. Function Optional Parameter
  13. Map f to List
  14. Complex Numbers
  1. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  2. Predefined Global Variables