Searching an array

I have an array of classes source[]

I can sort it like this
source.sort! { |x,y| x.fname <=> y.fname }

If I print it out it is sorted by 'fname'.

Now I would like to search it for different fnames but can't find an example of how to do that.
Can someone tell me how?

thanks,
Ralph

source.find {|x| x.fname == "foo"}
source.select {|x| x.fname == "foo"}

HTH

robert

···

2005/10/25, Ralph Smith <ralph@lkjlkj.com>:

I have an array of classes source

I can sort it like this
source.sort! { |x,y| x.fname <=> y.fname }

If I print it out it is sorted by 'fname'.

Now I would like to search it for different fnames but can't find an example of how to do that.
Can someone tell me how?

Ralph Smith wrote:

I have an array of classes source

I can sort it like this
source.sort! { |x,y| x.fname <=> y.fname }

If I print it out it is sorted by 'fname'.

Now I would like to search it for different fnames but can't find an example of how to do that.
Can someone tell me how?

thanks,
Ralph

I like grep eg.

results = source.grep(/.txt/)

returns a list (array) of entries that contain '.txt'. (including things like fred.txt.bak)

Array mixes in (includes) the methods in Enumerable which is where much of this magic is hiding.

Bill

Ralph Smith wrote:

I have an array of classes source

I can sort it like this
source.sort! { |x,y| x.fname <=> y.fname }

If I print it out it is sorted by 'fname'.

Now I would like to search it for different fnames but can't find an
example of how to do that. Can someone tell me how?

thanks,
Ralph

I like grep eg.

results = source.grep(/.txt/)

returns a list (array) of entries that contain '.txt'. (including
things like fred.txt.bak)

Unlikely that it works in this case as Ralf seems to have instances of a custom class in the array. If you want to make grep work with that you'd need to either implement #to_str for this custom class (which I'd find inappropriate) or do this

condition = lambda {|x| x.fname == "foo"}
class<<condition
  alias ===
end
source.grep condition

:slight_smile:

Array mixes in (includes) the methods in Enumerable which is where
much of this magic is hiding.

Yes, among them #inj... Ok, I'll keep my mouth shut.

Kind regards

    robert

···

Bill Mustard <bill@jrl.org> wrote: