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 (including max/min etc, if the entries define <=>).
  • 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

range 10..1 is not usable

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| ... }
Written on March 30, 2019, Last update on August 2, 2023
ruby loop iterate string