From: Joel VanderWerf Date: 2008-01-04T10:45:53+09:00 Subject: Re: Finding if an array contains a data type Sam Phoneix wrote: > Say I wanted to see if an array contained a number or not. Would I use > the match method? > > E.g. > > x=["a","b",2, "c"] > > puts("This array contains numbers") if x.match(/\d/) Another way, just for fun: x=["a","b",2, "c"] puts("This array contains numbers") unless x.grep(Numeric).empty? Let's take apart what that means: 1. The Enumerable#grep method uses the "matching" operator === to search for all matches to the argument, which are collected into a new array. 2. In this case, grep's argument is a class, so each element of x is matched using the following condition: Numeric === the_element. 3. When called on classes, === checks if the given object is a member of the class (or a descendent) or not. But this is not the most efficient solution since it has to pass over the entire collection (instead of stopping on the first match), and it makes a new array with the results. It's really only useful when you need all matches, for some reason. Otherwise, follow the suggestion to use #any? and #is_a? or #kind_of?. References: ri Module#=== ri Enumerable#grep -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407