Ruby loops

From wikinotes
Revision as of 14:48, 29 October 2021 by Will (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Keywords

next  # continue to next loop
redo  # redo current loop
break # exit loop

ranges

3.times { puts "hi!" }
3.upto(10) { |i| puts i }
('a'..'e').each {|char| puts char }
*(1..100).map {|x| puts x}
5.times do
  puts 'hi'
end
5.times {
  puts 'hi'
}
for i in 1..5
  puts 'hi'
end

each

animals = ['cat', 'dog', 'bear']
animals.each do |animal|
  puts animal
end
# animal IS NOT assigned within scope
['a', 'b', 'c'].each_with_index.map do |letter, index|
  puts "#{letter} at #{index}"
end

for in

animals = ["cat", "dog", "bear"]
for animal in animals
  puts animal
end
# animal IS assigned within scope

while

while i < 100
  puts i
  i += 1
end
var = var + 1  while var < 100