From: Robert Klemme Date: 2013-03-30T07:18:32+09:00 Subject: Re: Ruby Typing? --20cf30050e8a994c9404d917a634 Content-Type: text/plain; charset=ISO-8859-1 On Fri, Mar 29, 2013 at 5:38 PM, Joel Pearson wrote: > Sometimes it's best to let the errors occur, there's already a certain > amount of error-handling in Ruby. > > Anyway, this should do what you want: > > def Add_two_numbers(x,y) > [x,y].each { |num| > fail ArgumentError, "#{num} is not a number" unless num.is_a? Fixnum > } > x + y > end > Better use Integer for the test because Fixnums turn to Bignums from a certain number on. Using #to_int or Integer() is a simpler approach as it includes the exception throwing code with a meaningful error message already: irb(main):023:0> Integer("x") ArgumentError: invalid value for Integer(): "x" from (irb):23:in `Integer' from (irb):23 from /usr/bin/irb:12:in `
' irb(main):024:0> "x".to_int NoMethodError: undefined method `to_int' for "x":String from (irb):24 from /usr/bin/irb:12:in `
' Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/ --20cf30050e8a994c9404d917a634 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable



On Fri, Mar 29, 2013 at 5:38 PM, Joel Pearson <= ;lists@ruby-forum= .com> wrote:
Sometimes it's best to let the errors occur, there'= ;s already a certain
amount of error-handling in Ruby.

Anyway, this should do what you want:

def Add_two_numbers(x,y)
[x,y].each { |num|
fail ArgumentError, "#{num} is not a number" unless num.is_a? Fix= num
}
x + y
end=A0

Better use Integer for the test because Fi= xnums turn to Bignums from a certain number on. =A0Using #to_int or Integer= () is a simpler approach as it includes the exception throwing code with a = meaningful error message already:

irb(main):023:0> Integer("x")
ArgumentError: invalid value for Integer(): "x"<= /div>
=A0 =A0 =A0 =A0 from (irb):23:in `Integer'
=A0 =A0 =A0 =A0 from (irb):23
=A0 =A0 =A0 =A0 from /usr/bin/irb:12:in `<main>'= ;
irb(main):024:0> "x".to_int
No= MethodError: undefined method `to_int' for "x":String
=A0 =A0 =A0 =A0 from (irb):24
=A0 =A0 =A0 =A0 from /usr/bin/irb:12:in `<main>'


K= ind regards

robert

--
remember.guy do |as, often| as.you_can - without end<= br>http://blog.rubybestpract= ices.com/
--20cf30050e8a994c9404d917a634--