Comment

Comment by dragonwriter

While people have pointed out that this is not idiomatic:

  class Stuff
    def initialize
      @a_list = [1, 2, 3, 4]
    end

    def each
      for item in @a_list
        yield item
      end
    end
  end
I haven't seen anyone point out the deepest reason why: unlike in many languages, “for” is not a basic, low-level construct in Ruby, it is syntax sugar. That is:

  for x in y
    x.stuff
    more_stuff
  end
is sugar for:

  y.each do |x|
    x.stuff
    more_stuff
  end
(Also, for quite a long time, for...in also had runtime overhead , so it was slower syntactic sugar.)

for...in is rarely used (it is syntactic sugar that is neither more concise bor more specific in intent, but more familiar to people with experience in non-Ruby languages), and mostly on scripts that consume but don’t implement collections. If you are getting deep enough to be implementing an #each method for a custom collection, that's an odd place to use for.

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton