Sam said:
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/)
I'm a real beginner at ruby, so simple explanations for simple folk
please. I appreciate your help.
Nice try, but match matches strings and you're wanting numbers.
Note that the Array class includes the Enumerable module, so all methods
in Enumerable are available in Array. Enumerable has a method called
"any?" that we can use. Here's what ri says about Enumerable#any?
$ ri Enumerable#any?
-------------------------------------------------------- Enumerable#any?
enum.any? [{|obj| block } ] => true or false
------------------------------------------------------------------------
Passes each element of the collection to the given block. The
method returns true if the block ever returns a value other than
false or nil. If the block is not given, Ruby adds an implicit
block of {|obj| obj} (that is any? will return true if at least
one of the collection members is not false or nil.
%w{ ant bear cat}.any? {|word| word.length >= 3} #=> true
%w{ ant bear cat}.any? {|word| word.length >= 4} #=> true
[ nil, true, 99 ].any? #=> true
So, here's how to use it:
irb(main):001:0> x=["a","b",2, "c"]
=> ["a", "b", 2, "c"]
irb(main):002:0> x.any? {|p| p.is_a? Numeric}
=> true