On Fri, Mar 29, 2013 at 5:06 PM, John n/a <lists / ruby-forum.com> wrote:

> Hi everyone. I'm very new to ruby development. I coming form .Net side
> of things. Is there any way in ruby to verify the type of whatever
> parameter your passing to a method and give the user a good message.


Welcome to the wonderful world of Ruby!

Your Ruby experience will be much more smoothly if you get rid of the
static typing mindset.  It's not the way people use Ruby.  But many people
coming from statically typed languages fear that their Ruby programs will
be totally unsafe if they do not ensure types are enforced.

You'll find a lot of explanations under the term "duck typing".


> For
> example:
>
> def Add_two_numbers(x,y)
>     ....if type of x is not integer
>          throw an error "x was expected to be an integer and is not"
>    .....if type of y is not an integer
>        throw an error "y was expected to be an integer and is not"
> end
>

I once blogged about creating classes which represent numbers.  The central
concept revolves around method #coerce.
http://blog.rubybestpractices.com/posts/rklemme/019-Complete_Numeric_Class.html


In the specific case of your method above, I'd simply do

def add_two_numbers(x, y)
  x.to_int + y.to_int
end

This will reliably fail if x or y do not represent integer values.

When i just hit a bug where i was expecting an array of comments and
> instead a single comment was passed (in the constructor). The code
> exploded with i tried to do "@comments << comments[0]" because @comments
> was not an array with an error message like "undefined function '<<'
> which took me awhile to figure out. Want to try to prevent this in the
> future if possible.
>

Writing tests helps a great deal avoiding that. :-)

Kind regards

robert


-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/