Home > Software engineering >  Is there a `with_self` or similar block for a Ruby enum?
Is there a `with_self` or similar block for a Ruby enum?

Time:12-21

Similar to how, in Ruby, you can do

[1, 2, 3].each.with_index { |num, index| }

I'd like to chain that to also add a reference to the top level array without having to assign said array to a different variable before the block, like so:

[1, 2, 3].each.with_index.with_self { |num, index, array| }

Does such a method exist, or any alternatives outside of the obvious of having a top-level variable set?

My specific case is off a Ruby script that I'd like to golf as much as readably possible. I have an input file with rows, and I'm reading the file like so:

STDIN.each_line.with_index

But also need to back-reference the original "array", but because of each_line the array becomes an Enumerator. I could break it up and parse the pieces of course, but trying to keep the script concise. The with_self would be perfect, but it doesn't appear to exist.

  •  Tags:  
  • ruby
  • Related