[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

array.index(obj, start)?

Esmail

12/26/2007 6:48:00 PM

Hi

array.index(obj) will return the index of the item in the array.

I am unable to find a version of this that allows one to specify
a starting index in place of the default 0 start, is there such a
function?


Let's say I have a text file that contains multiple records of some sort.
Each record has a unique identifier, but ends with the same character,
say '<'. So, the identifiers are unique, but then end of record markers
are not.

I read this file into an array of strings and am trying to delete
one or more of these records. The records may not be in order of
deletion. My idea is to set the given range to nil and then use compact!
to delete the lines when I'm done with the "deletions".

So, one sequence might be like this:

start=ar.index(starting_name) will give me the starting index
end=ar.index('<', start) would give me the immediate next
end tag (there may be others.)
ar[start...end]=nil
ar.compact!

Comments/suggestions? I really like Ruby but I am not yet
proficient with it.

Thanks.
2 Answers

Esmail

12/26/2007 8:25:00 PM

0

ok this seems to work, but I am curious if there is a
better, perhaps more Ruby'ish way to do this.

start=ar.index(starting_name)
end=ar[start+1..-1].index('<')
ar[s..start+end]=nil

and doesn't even require the compact! at the end.

Is there a better/nicer/more Ruby way?

MonkeeSage

12/27/2007 2:22:00 AM

0

On Dec 26, 12:48 pm, Esmail <ebonak_de...@hotmail.com> wrote:
> Hi
>
> array.index(obj) will return the index of the item in the array.
>
> I am unable to find a version of this that allows one to specify
> a starting index in place of the default 0 start, is there such a
> function?
>
> Let's say I have a text file that contains multiple records of some sort.
> Each record has a unique identifier, but ends with the same character,
> say '<'. So, the identifiers are unique, but then end of record markers
> are not.
>
> I read this file into an array of strings and am trying to delete
> one or more of these records. The records may not be in order of
> deletion. My idea is to set the given range to nil and then use compact!
> to delete the lines when I'm done with the "deletions".
>
> So, one sequence might be like this:
>
> start=ar.index(starting_name) will give me the starting index
> end=ar.index('<', start) would give me the immediate next
> end tag (there may be others.)
> ar[start...end]=nil
> ar.compact!
>
> Comments/suggestions? I really like Ruby but I am not yet
> proficient with it.
>
> Thanks.

s = "stuff<more stuff<this is sure alot of stuff"
a = s.split("<")
a.delete_at(1)
s = a.join("<")
p s # => "stuff<this is sure alot of stuff"

Regards,
Jordan