What's the idiom in Ruby when you want to have a default argument to a function, but one that is dependent on another parameter / another variable? For example, in Python, an example is:
def insort_right(a, x, lo=0, hi=None):
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if x < a[mid]: hi = mid
else: lo = mid+1
a.insert(lo, x)
Here, if hi
is not supplied, it should be len(a)
. You can't do len(a)
in the default argument list, so you assign it a sentinel value, None, and check for that. What would the equivalent be in Ruby?
When defining a method in Ruby, you can define default values for optional parameters. When calling the method, Ruby sets the default value to the local variable as if the user would have provided this argument. This automatism is really useful to support optional parameters with sensible defaults without having to think much about this.
Another thing about keyword arguments is that they are very explicit about the arguments you are missing. You can also combine keyword arguments with regular arguments. One strategy I’ve been observing on Ruby built-in methods is that new versions tend to add new, optional arguments, as keyword arguments.
When calling the method, Ruby sets the default value to the local variable as if the user would have provided this argument. This automatism is really useful to support optional parameters with sensible defaults without having to think much about this. It even works exactly the same with the new keyword arguments introduced in Ruby 2.0.
So what this error means is that we gave the method three arguments but it expects only one argument, hence the argument error. Default parameters as their name suggests, basically set a default value in case none is provided. There’s always a fallback option with these parameters.
def foo(a, l = a.size)
end
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