Hi,
I have a method & i wanna pass around 25 parameters to it and i hav to
make string from that, as follows…
def method1(email, b_day, b_month, b_year, gender, f_name, l_name,
mdl_name, title, country, …)
params =
“email=#{email}&birth_day=#{b_day}&birth_year=#{b_year}…”
end
it looks very odd when passing these many parameters. Is there any other
option that I can mention only mandatory args in the method & remaining
all are in single argument or something like that?
thanks in advance,
avantec
On Aug 10, 2011, at 8:10 AM, Avantec V. wrote:
Hi,
I have a method & i wanna pass around 25 parameters to it and i hav to
make string from that, as follows…
I wouldn’t recommend writing a method that takes 25 parameters, but
moving along…
option that I can mention only mandatory args in the method & remaining
all are in single argument or something like that?
Yes, you can do this:
def method1(required, required, required, *args)
Which Ruby will fill *args with remaining arguments as an array (empty
array if there are none):
def test(a,b,*args)
p a,b,args
end
=> nil
test(1,2,3,4,5)
1
2
[3, 4, 5]
Another option is to pass either an object in, or a Hash. I’d recommend
this path if the data you’re dealing with relates to each other (which
it looks like it does).
Regards,
Chris W.
http://www.twitter.com/cwgem
Another option is to pass either >an object in, or a Hash. I’d >recommend
this path if the data >you’re dealing with relates to >each other (which
it
looks like it >does).
+1
Read about a code smell named Primitive Obsession. If the set of params
are
part of a higher level concept of your program, such as UserContact or
something similar, you should create an object for that. It can be a
full
fledged class or a struct, for example.
Jesus.
On Aug 10, 11:10am, Avantec V. [email protected] wrote:
end
it looks very odd when passing these many parameters. Is there any other
option that I can mention only mandatory args in the method & remaining
all are in single argument or something like that?
Use options hash.
def method1(options)
email = options[:email]
b_day = options[:b_day]
…
Thomas S. wrote in post #1015985:
Use options hash.
def method1(options)
email = options[:email]
b_day = options[:b_day]
…
And note there is special syntax available when calling a method like
this: if the last argument is a hash, you don’t need to wrap it in
{braces}
method1 :email=>“[email protected]”, :b_day=>“1900/01/01”
If you’re writing ruby 1.9 code (and you don’t care about 1.8
compatibility), and all your keys are symbols, there’s another syntax:
method1 email: “[email protected]”, b_day: “1900/01/01”