Dave Burt
3/2/2005 6:34:00 AM
"gabriele renzi" <surrender_it@remove-yahoo.it> ha scritto:
> Assaph Mehr ha scritto:
>> . puts words.select { |word| word =~ /#{suffix}$/ }
>
> for String there is a special method of Enumerable, since this is an
> important case:
> puts words.grep(/suffix$/)
Cool! It's not a special case, it's a case-equality match:
-------------------------------------------------------- Enumerable#grep
enum.grep(pattern) => array
enum.grep(pattern) {| obj | block } => array
------------------------------------------------------------------------
Returns an array of every element in _enum_ for which +Pattern ===
element+. If the optional _block_ is supplied, each matching
element is passed to it, and the block's result is stored in the
output array.
a = [nil, 1, 3.5, 'a', nil, 10**100, [], {}, 'b', 'c']
a.grep(NilClass).size #=> 2
a.grep(String) #=> ['a', 'b', 'c']
a.grep(Numeric) #=> [1, 3.5, 10000...]
So you can do regex-matches on string arrays, and kind_of?-matches, and
equality-matches.
Cheers,
Dave