This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Groovy and the fly likes Closure Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Languages » Groovy
Bookmark "Closure Question" Watch "Closure Question" New topic
Author

Closure Question

Brian Mooney
Greenhorn

Joined: Sep 30, 2010
Posts: 3
Hi,

Have been looking at Groovy recently and am interested in trying to learn it properly.
Was just trying some file manipulation using groovysh and I'm a little puzzled by something that I'm seeing.

I was simply trying to add line numbers to the contents of a file as per:

But when reviewing the output, I'm seeing:
1: 1st Line
2: 2nd Line
3: Some random text
4: Random Stuff
5: Last line
6: Well almost!!


If I update the code as per below (initialising the Integer i to 1 as opposed to 0):

I get the same output:
1: 1st Line
2: 2nd Line
3: Some random text
4: Random Stuff
5: Last line
6: Well almost!!


My question is why doesnt the first code block index the lines from zero?
To get the desired result, I have to edit the code as such:

which results in:
0: 1st Line
1: 2nd Line
2: Some random text
3: Random Stuff
4: Last line
5: Well almost!!


This is of course very trivial but I'm more wondering where my understanding of what is happening is falling down as I would have expected the final result to be produced by the very first code block.

Appreciate any correspondance



Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30580
    
154

Brian,
This does what you want. Passing the desired start index as a parameter prevents Groovy from using a default of 1 for the line number.


The eachLine method is defining the second argument to be the line number. It ignores any requests you make of i. For example, if you change i++ to i+=2, you get the same behavior 1-6 as before because eachLine is helpfully setting i to the line number for you.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Brian Mooney
Greenhorn

Joined: Sep 30, 2010
Posts: 3
Indeed you're right. I was getting confused about the inputs for the eachLine() method.

Appreciate the response and help on the matter.

Regards,
Brian
 
GeeCON Prague 2014
 
subject: Closure Question