String as optional parameter for method?

Hi All,
I have one method like def hello(int,string)
Now i want that if user pass int value or string value then it should
search on the basis of one of those.

means i want both as optional parameter.
Please tell me how to do this in ROR.
Thanks
Varun

-----Original Message-----
From: [email protected] [mailto:[email protected]]
Sent: Wednesday, May 14, 2008 8:34 AM
To: ruby-talk ML
Subject: string as optional parameter for method?

Hi All,
I have one method like def hello(int,string)
Now i want that if user pass int value or string value then it should
search on the basis of one of those.

So as far as I understand you want methods overloaded on the parameter
type? Ruby does not support method overloading directly. One way you can
do it is something like that:

def hello(arg)
case arg in
when String then hello_with_string(arg)
when Integer then hello_with_integer(arg)
else raise “Unsupported parameter type”
end
end

Ruby methods may have default parameters, however it may be not what you
are after as this facility does not guarantee parameter types.

Gennady.

-------- Original-Nachricht --------

Datum: Thu, 15 May 2008 00:33:37 +0900
Von: Varun G. [email protected]
An: [email protected]
Betreff: string as optional parameter for method?

Posted via http://www.ruby-forum.com/.
Dear Varun,

maybe something like this ?

def hello(first=nil,second=nil)
if first.class==Fixnum and second.class==String
p ‘you entered something for both int and string’
elsif first.class==Fixnum
p ‘you entered something for int’
elsif first.class==String and second==nil
p ‘you entered something for string’
else
p ‘come on, read the manual!’
end
end

p hello(5,‘string’)
p hello(5)
p hello(‘string’)
p hello(5.78,nil)
p hello()

Best regards,

Axel

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs