Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby default argument idiom

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?

like image 876
Claudiu Avatar asked Oct 06 '10 18:10

Claudiu


People also ask

How do you set default values for optional parameters 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.

What are keyword arguments in Ruby?

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.

What is automatism in Ruby and how does it work?

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.

What does the argument error mean in Python?

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.


1 Answers

def foo(a, l = a.size)
end
like image 63
horseyguy Avatar answered Oct 04 '22 21:10

horseyguy