Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

searching an array

0 views
Skip to first unread message

Ralph Smith

unread,
Oct 25, 2005, 8:23:04 AM10/25/05
to

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


Robert Klemme

unread,
Oct 25, 2005, 8:38:56 AM10/25/05
to
2005/10/25, Ralph Smith <ra...@lkjlkj.com>:

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

HTH

robert


Bill Mustard

unread,
Oct 25, 2005, 11:05:56 AM10/25/05
to

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

Robert Klemme

unread,
Oct 25, 2005, 11:57:11 AM10/25/05
to
Bill Mustard <bi...@jrl.org> wrote:
> 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

:-)

> 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

0 new messages