#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2005
    Posts
    83
    Rep Power
    10

    Array Class: Exception


    Can someone explain how to detect if the elements of an array are non-numeric? I want to raise an exception for arrays in which the elements are not numbers.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2004
    Location
    Constant Limbo
    Posts
    989
    Rep Power
    363
    Here is an example using map.
    You could do the same with .map, or .collect
    Code:
    irb(main):007:0> a = [1,2,3,4,5]
    => [1, 2, 3, 4, 5]
    irb(main):008:0> b = [1,2,3,4,'a']
    => [1, 2, 3, 4, "a"]
    irb(main):009:0> a.each { |x| raise "Invalid!!" unless x.kind_of? Numeric }
    => [1, 2, 3, 4, 5]
    irb(main):010:0> b.each { |x| raise "Invalid!!" unless x.kind_of? Numeric }
    RuntimeError: Invalid!!
            from (irb):10
            from (irb):10:in `each'
            from (irb):10
            from :0
    True happiness is not getting what you want, it's wanting what you've already got.

    My Blog

IMN logo majestic logo threadwatch logo seochat tools logo