How to Iterate the Right Way
If any of you have written code in the last year that had an explicit loop […], you don’t understand collections. David West.
see also
- Ruby vs Python comes down to the for loop / HN - Ruby inherits it’s approach to flow control from Smalltalk, while Python comes from a C/Algol-like heritage.
- HN - Once you implement
each
,include Enumerable
is all it takes to get the full set of collection methods (includingmax
/min
etc, if the entries define<=>
).
- HN - Once you implement
- No Stinking Loops - The K language provides constructs like each, over, and scan to perform what would be looping behavior in other languages.
see also Enumerable
As a side note…
negative loop in ruby
for i in 10.downto 0
puts i
end
or
10.step(0, -1){ |i| puts i}
or
10.downto 0 do |i|
puts i
end
Natural forward loop
for i in 1..10
...
end
Iterate on string
"input".each_char { |c| ... }
"input".chars.map { |c| ... }
"input".chars.each_with_index { |c,i| ... }
"input".bytes { |c| ... }
Send method to each object in Array
array.each(&:some_method)
# Which is shorthand for
array.each(&Proc.new { |x| x.some_method })
# Use that version if you need to pass parameters to the method.
Written on March 30, 2019, Last update on June 11, 2024
ruby
loop
iterate
string