testing argument type and duck typing, newbie question

R

Raphael Bauduin

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
 
T

ts

R> I have a method taking one argument that can be an integer or a string.
R> How do I test the argument to know if it's a string or an integer? All
R> the duck typing things I've read make me wonder what's the best way
R> 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
 
G

gabriele renzi

il Tue, 18 Nov 2003 13:34:32 +0100, Raphael Bauduin
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 :)
RuntimeError: wrong parameters!
from (irb):2:in `f'
from (irb):4
or if you wont you can get StrongTyping and do:

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

Zachary P. Landau

--yEPQxsgoJgBvi8ip
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable
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= =20
the duck typing things I've read make me wonder what's the best way=20
to determine if the argument is an integer or a string.....
[...]

or if you wont you can get StrongTyping and do:
=20
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

--=20
Zachary P. Landau <[email protected]>
GPG: gpg --recv-key 0x24E5AD99 | http://kapheine.hypa.net/kapheine.asc

--yEPQxsgoJgBvi8ip
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (GNU/Linux)

iD8DBQE/uk/LCwWyMCTlrZkRAiA2AJwNDHaiKTaZljDVkBfUNiQdCj4f7QCdHHaU
lsYQy/1dIuTgmPs6yJvKV8g=
=iSje
-----END PGP SIGNATURE-----

--yEPQxsgoJgBvi8ip--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top