Testing argument type and duck typing, newbie question

Hi,

I have a method taking one argument that can be an integer or a string.
How do I test the argument to know if it’s a string or an integer? All
the duck typing things I’ve read make me wonder what’s the best way
to determine if the argument is an integer or a string…

Thanks for helping me clarifying this.

Raph

I have a method taking one argument that can be an integer or a string.
How do I test the argument to know if it's a string or an integer? All
the duck typing things I've read make me wonder what's the best way
to determine if the argument is an integer or a string.....

Well, it really demand on what you want to do.

One possibility is to call the global function Integer, if it give an
error you have possibly a String : now you can call #to_str on this object
(if you want catch some errors) or you can convert your argument to a
String by calling #to_s

Guy Decoux

Hi,

I have a method taking one argument that can be an integer or a string.
How do I test the argument to know if it’s a string or an integer? All
the duck typing things I’ve read make me wonder what’s the best way
to determine if the argument is an integer or a string…

you don’t want duck typing :slight_smile:

def f(a,b)
raise ‘wrong parameters!’ unless a.is_a?String and b.is_a?Numeric
end
=> nil
f(1,2)
RuntimeError: wrong parameters!
from (irb):2:in `f’
from (irb):4
f(‘yes’,2)
=> nil

or if you wont you can get StrongTyping and do:

def f(a,b)
expect(String,a,Integer,b)
end

···

il Tue, 18 Nov 2003 13:34:32 +0100, Raphael Bauduin raphael.bauduin@be.easynet.net ha scritto::

I have a method taking one argument that can be an integer or a string.
How do I test the argument to know if it’s a string or an integer? All
the duck typing things I’ve read make me wonder what’s the best way
to determine if the argument is an integer or a string…

[…]

or if you wont you can get StrongTyping and do:

def f(a,b)
expect(String,a,Integer,b)
end

He wanted a single argument with multiple possibilities. With
StrongTyping, that would be:

def f(a)
expect(a, [String, Integer])
end

···


Zachary P. Landau kapheine@hypa.net
GPG: gpg --recv-key 0x24E5AD99 | http://kapheine.hypa.net/kapheine.asc

Hi –

···

On Tue, 18 Nov 2003, gabriele renzi wrote:

il Tue, 18 Nov 2003 13:34:32 +0100, Raphael Bauduin > raphael.bauduin@be.easynet.net ha scritto::

Hi,

I have a method taking one argument that can be an integer or a string.
How do I test the argument to know if it’s a string or an integer? All
the duck typing things I’ve read make me wonder what’s the best way
to determine if the argument is an integer or a string…

you don’t want duck typing :slight_smile:

Then he’d better avoid Ruby :slight_smile:

David


David Alan Black
home: dblack@wobblini.net # New email address
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav