On Fri, Mar 29, 2013 at 5:06 PM, John n/a [email protected] 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
coming from statically typed languages fear that their Ruby programs
be totally unsafe if they do not ensure types are enforced.
You’ll find a lot of explanations under the term “duck typing”.
…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”
I once blogged about creating classes which represent numbers. The
concept revolves around method #coerce.
In the specific case of your method above, I’d simply do
def add_two_numbers(x, y)
x.to_int + y.to_int
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” 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.