#---Loops---
Loops are how you run a piece of code repeatedly as long as a condition is true, or for a specific number of times.
Ruby has several ways to loop.
Runs the supplied code block as long as the condition is true.
i = 0
while i <= 3 # do is optional
i += 1
end
p i # => 4
Runs the supplied code block as long as the condition is false.
i = 100
while i > 11
i -= 1
end
p i # => 11
Both while
and until
support this inline form.
i = 100
i -= 1 until i <= 42
p i # => 42
Use for..in
to loop over an array or a hash.
for ele in ['a', 'b', 'c']
print ele
end # => abc
for item in {a: 'aa', b: 'bb'}
p item
end
## => [:a, "aa"]
## => [:b, "bb"]
A better way to iterate over an array or a hash is the
each
method available on them.
For every element it calls the block with
that element.
[11, 22, 33].each { |e| print e }
## => 112233
{a: 'aa', b: 'bb'}.each { |k, v| p "k: #{k}, v: #{v}" }
## => "k: a, v: aa"
## => "k: b, v: bb"
each
is available on many more iterable types like
Dir
, IO
, Range
, Set
etc:
Dir.new(Dir.home).each { |e| p e}
## => lists all files and dirs in your home dir.
('a'..'j').each { |e| print e } # => abcdefghij
You can also create a
loop using the Kernel module’s loop
method
which you can use without including the module.
i = 1
loop do
print i
break if i >= 9
i += 1
end
## => 123456789
If you want to do a thing an ‘n’ number of times, then
there’s the Integer class’s times
method.
10.times { p "Life's good!" }
Note: The above 3 - each
, loop
and times
- are all
ruby methods, whereas while
, until
and for
are all
ruby keywords.
For enumerable types, prefer the each
method.
For others, prefer the loop
or the n.times
methods.
Ruby folks rarely use for
, while
and until
.
But the most common way of looping is actually the
various methods defined in the Enumerable
module which
is available on all enumerables.
These are specialized loops like map
, find_all
,
any?
, zip
, group_by
, min
, max
, reduce
,
grep
etc.
These are discussed here.