John Joyce
4/28/2007 5:06:00 PM
On Apr 29, 2007, at 1:10 AM, Robert Klemme wrote:
> On 28.04.2007 15:27, John Joyce wrote:
>> On Apr 28, 2007, at 9:50 PM, Robert Klemme wrote:
>>> On 28.04.2007 09:06, Robert Dober wrote:
>>>> On 4/28/07, Robert Dober <robert.dober@gmail.com> wrote:
>>>>> > love,
>>>>> > John Joyce
>>>>> >
>>>>> >
>>>>> ARGF.readlines.each_with_index{
>>>>> | line, idx |
>>>>> puts "%3d %s" % [ idx.succ, line ]
>>>>> }
>>>>> HTH
>>>>> Robert
>>>> But Robert's solution is nicer, I did not know about
>>>> ARGF.lineno, and
>>>> have overlooked his solution, sorry!
>>>
>>> :-) Thank you! Btw, you can also do ARGF.each_with_index so you
>>> do not have to read the whole file into mem before printing it.
>>>
>>> Kind regards
>>>
>>> robert
>> This .each_with_index seems to be an invaluable method... I'd like
>> to know more about it. Can anyone give a little more detail on how
>> each_with_index works? The pickaxe covered it too briefly for my
>> feeble mind, but clearly it's got legs.
>
> There's not much to it. It's defined in module Enumerable and
> yields the current element plus a count to the block. You can
> imagine it implemented like this but of course it's written in C:
>
> module Enumerable
> def ewi
> c=0
> each {|x| yield x, c; c+=1}
> end
> end
>
> Kind regards
>
> robert
>
So let me see if I got this close to straight:
each_with_index is like each in that it alows you to iterate through
the array, but additionally hands over a counter that is also
incremented?! If this is the deal, then I'm gonna have to go to rehab
because of that method. How useful it will be. I think for the last
week I've been wanting exactly that in more places than I can think
of. Where I had been building iterating blocks with some externally
initialized counter. I knew I'd missed something golden. Hadn't
looked into the Enumerator lib yet. Been forging through the File an
IO stuff.