Search code examples
rubymethodsargumentsdefault

Dealing with 3 or more default arguments Ruby


I've seen a few examples of passing default arguments when creating methods, but none of them seem to address if you want to substitute only the first and third argument... here's an example

def foo(a = 1, b = 2, c = 3)
    puts [a, b, c]
end

foo(1, 2) 
#=> [1, 2, 3]

When I try to assign a=5 and c=7 and keep b its default value like this:

foo(a=5,c=7) 

I get

=> 5,7,3

but I expect 5,2,7

what is the correct way to accomplish this?


Solution

  • Using keyword arguments?

    def foo(a: 1, b: 2, c: 3)
      puts [a, b, c]
    end
    
    foo(a: 5, c: 7)