Reputation: 2827
1) I have a method
def self.createobj(api_key, amnt, commentstr, orderid, order_creation_date, orderfullfilmentdate)
.....
end
2) I want to create a error_str of all the parameters passed to this function ...
2.1) Something like
errorstr = "api_key: " + api_key.to_s + " amnt: " + amnt.to_s + " commentstr: " + commentstr.to_s + " orderid: " + orderid.to_s + " order_creation_date: " + order_creation_date.to_s + " orderfullfilmentdate: " + orderfullfilmentdate.to_s
2.2) So I created another method
def self.get_params_str(a)
str = ""
a.each do |a|
str = str + a.to_s
end
return str
end
2.3) So I call this new method from createobj. Something like
def self.createobj(api_key, amnt, commentstr, orderid, order_creation_date, orderfullfilmentdate)
errorstr = get_params_str(args)
.....
end
3) But I get error undefined local variable or method `args' for #. Shouldn't args have all parameters?
Please advice.
Upvotes: 0
Views: 2011
Reputation: 3020
As stated in the other responses there's no available variable like args
that provides the names of the arguments for the method, however if you're on Ruby 1.9.2 (I can't confirm if exist on 1.9.1 as well) you have the method parameters
so you can do something like this:
def foo(a, b, c)
errorstr = method(:foo).parameters.map{|p| "#{p.last}: #{eval p.last.to_s}" }.join(', ')
puts errorstr
end
foo(1, 2, 3) #=> a: 1, b: 2, c: 3
Upvotes: 1
Reputation: 49104
What you're trying to do (trying to use a magic var called args that will hold all of the arguments) doesn't work in this way in Ruby.
A method can have optional args:
def my_method(*args)
....
# the array args will have 0 or more elements, depending on how many
# were in the method invocation.
end
But if a method has specific (required) args, as in your example, then there is no other way to get at them.
Added If you're willing to change the definition of your method to use the work-around for named arguments, then the args will arrive as an associative array and you can then send them to your get_params_string
Or better, redefine your get_params_string
to take a variable arg list
def self.get_params_str(*a)
str = ""
a.each do |a|
str = str + a.to_s
end
return str
end
# Then call it from your main method:
def self.createobj(api_key, amnt, commentstr, orderid,
order_creation_date, orderfullfilmentdate)
errorstr = get_params_str(api_key, amnt, commentstr, orderid,
order_creation_date, orderfullfilmentdate)
.....
end
See a useful post
Upvotes: 2
Reputation: 39558
args
would only contain the parameters if your method definition was something like def self.createobj(*args)
. Without that args
isn't defined.
You will need to manually pass all of the parameters to get_params_str
. You will need to pass them as an array, i.e get_params_str([api_key, amnt, commentstr, ...])
unless you change get_params_str
's method signature to def self.get_params_str(*a)
(which puts all of the parameters passed to get_params_str
into a single array`).
Upvotes: 1