I am trying to set up default parameter and I would like to skip passing an argument and assign particular arguments in the function call. But, I am not able to get the desired output.
require "json"
def stun(voltage = 0,frequency = 0,range = "",scope = "")
body = {
:voltage => voltage,
:frequency => frequency,
:range => range,
:scope => scope
}
response = body.to_json
end
stun(voltage = 1,frequency = 2,scope = "universal")
As you can see in the code above, I am trying to assign value to scope while keeping the range parameter an empty string. I am getting the following response.
"{\"voltage\":1,\"frequency\":2,\"range\":\"universal\",\"scope\":\"\"}"
My desired output would be to have range as an empty string and scope as "universal"
Key Points to Remember For Default Argument The overwriting of arguments take place when the calling function provides values for them. For example, calling of function sum(10, 15, 25, 30) facilitates overwriting of the value of z and w to 25 and 30 respectively.
In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).
In Ruby, all arguments are required when you invoke the method. You can't define a method to accept a parameter and call the method without an argument. Additionally, a method defined to accept one parameter will raise an error if called with more than one argument.
You've set up default values for the arguments, but you're still using positional arguments, the first argument will always go to voltage
, the second to frequency
, the third to range
, the fourth to scope
. Since you are passing 3 arguments, you end up passing voltage
, frequency
, and range
.
Those equal signs in the method call, aren't doing what you think. Instead of telling ruby which parameter is getting assigned, you are creating a local variable with those names:
stun(voltage = 1,frequency = 2,scope = "universal")
puts [voltage, frequency, scope].inspect # => [1, 2, "universal"]
Ruby does have a way, with named parameters, to do what you want though:
def stun(voltage: 0, frequency: 0, range: "", scope: "")
body = {
:voltage => voltage,
:frequency => frequency,
:range => range,
:scope => scope
}
response = body.to_json
end
puts stun(voltage: 1, frequency: 2, scope: "universal")
# => {"voltage":1,"frequency":2,"range":"","scope":"universal"}
This is available (I believe) since Ruby 2.0. If you use these though, you'll always need to pass the parameters with their names, for instance:
stun(1, 2, "", "universal")
raises wrong number of arguments (given 4, expected 0)
now. This isn't a bad thing, in my opinion, just something to keep in mind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With