kel.o
kel.o

Reputation: 139

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?

Upvotes: 2

Views: 539

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369604

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...

That's because it is impossible.

Default arguments get bound left-to-right. I wrote more about how arguments get bound to parameters in an answer to these questions:

Upvotes: 1

Ursus
Ursus

Reputation: 30071

Using keyword arguments?

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

foo(a: 5, c: 7) 

Upvotes: 4

Related Questions