Ruby loops: Difference between revisions
From wikinotes
(→ranges) |
No edit summary |
||
Line 1: | Line 1: | ||
= Keywords = | |||
<blockquote> | |||
<syntaxhighlight lang="bash"> | |||
next # continue to next loop | |||
redo # redo current loop | |||
break # exit loop | |||
</syntaxhighlight> | |||
</blockquote><!-- Keywords --> | |||
= ranges = | = ranges = | ||
< | <blockquote> | ||
<syntaxhighlight lang="ruby"> | |||
3.times { puts "hi!" } | 3.times { puts "hi!" } | ||
3.upto(10) { |i| puts i } | 3.upto(10) { |i| puts i } | ||
('a'..'e').each {|char| puts char } | ('a'..'e').each {|char| puts char } | ||
*(1..100).map {|x| puts x} | *(1..100).map {|x| puts x} | ||
</ | </syntaxhighlight> | ||
< | <syntaxhighlight lang="ruby"> | ||
5.times do | 5.times do | ||
puts 'hi' | puts 'hi' | ||
end | end | ||
</ | </syntaxhighlight> | ||
< | |||
<syntaxhighlight lang="ruby"> | |||
5.times { | 5.times { | ||
puts 'hi' | puts 'hi' | ||
} | } | ||
</ | </syntaxhighlight> | ||
< | |||
<syntaxhighlight lang="ruby"> | |||
for i in 1..5 | for i in 1..5 | ||
puts 'hi' | puts 'hi' | ||
end | end | ||
</ | </syntaxhighlight> | ||
</blockquote><!-- ranges --> | |||
= each = | = each = | ||
<blockquote> | |||
<source lang="ruby"> | <source lang="ruby"> | ||
animals = ['cat', 'dog', 'bear'] | animals = ['cat', 'dog', 'bear'] | ||
Line 37: | Line 51: | ||
end | end | ||
</source> | </source> | ||
</blockquote><!-- each --> | |||
= for in = | = for in = | ||
<blockquote> | |||
<source lang="ruby"> | <source lang="ruby"> | ||
animals = ["cat", "dog", "bear"] | animals = ["cat", "dog", "bear"] | ||
Line 46: | Line 62: | ||
# animal IS assigned within scope | # animal IS assigned within scope | ||
</source> | </source> | ||
</blockquote><!-- for in --> | |||
= while = | = while = | ||
<blockquote> | |||
<source lang="ruby"> | <source lang="ruby"> | ||
while i < 100 | while i < 100 | ||
Line 58: | Line 76: | ||
var = var + 1 while var < 100 | var = var + 1 while var < 100 | ||
</source> | </source> | ||
</blockquote><!-- while --> |
Latest revision as of 14:48, 29 October 2021
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' end5.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 endvar = var + 1 while var < 100