From: Ben Giddings Date: 2009-08-21T01:25:29+09:00 Subject: Re: extending ruby - handling errors On Thursday 20 August 2009 11:49:03 Jason Lillywhite wrote: > I want to raise an ArgumentError, "Function only takes numeric objects." > if a non-numeric argument is passed to the existing Ruby method, > Numeric.ceil. ... > irb(main):009:0> "foo".ceil > NoMethodError: undefined method `ceil' for "foo":String > from (irb):9 Right, because "foo" is a String, and Strings aren't numerics. If you want all non-numerics to recognize that "ceil" is a valid call, but only for Numerics, you'd need to provide "ceil" to all objects, then override it for numerics: irb(main):001:0> class Object irb(main):002:1> def ceil irb(main):003:2> raise ArgumentError, "not a numeric!" irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> "Foo".ceil ArgumentError: not a numeric ... irb(main):005:0> (3.14).ceil => 4 This is probably the wrong approach though. You shouldn't load up "Object" so it knows about random other methods that it's subclasses define, you should just catch NoMethodError in an appropriate spot. For example: def calculate_bounding_box(width, height) begin width_bound = width.ceil height_bound = height.ceil rescue NoMethodError raise ArgumentError, "width and height must be numeric" end width_bound * height_bound end Ben