Helio Ha
Helio Ha

Reputation: 79

Default Value vs. Keyword Argument

Can someone explain me the difference between using a default value for an argument and using keyword argument?

Default Value

def test1(var1, var2="2", var3=3)
  puts "#{var1} #{var2} #{var3}"
end

test1(1)         # => 1 2 3
test1(1, "2", 3) # => 1 2 3

Keyword Argument

def test2(var1, var2: "2", var3: 3)
  puts "#{var1} #{var2} #{var3}"
end

test2(1)         # => 1 2 3
test2(1, "2", 3) # => 1 2 3

I can't see any difference between them but I feel that I'm missing something because I've read that the Keyword Argument was a much-awaited feature for ruby 2.0

Upvotes: 6

Views: 2370

Answers (2)

Incerteza
Incerteza

Reputation: 34884

Apart of the given answer, in case of keyword arguments you can use them in a different order, whereas default arguments must be used in the order they've been defined.

Upvotes: 2

David Grayson
David Grayson

Reputation: 87406

The method bodies can look pretty similar, but the main difference is in how you would call the method.

Either method can be called with no arguments, since you specified defaults, so the code for calling the methods could just look like this:

test1
test2

But if you want to override the default when you call the methods, and set var1 to "foo", you would need to write something like this:

test1("foo")
test2(var1: "foo")

The line calling test2 above is syntactic sugar for:

test2({:var1 => "foo"})

To change a keyword argument, you have to pass a hash in as the last argument and one of the hash's keys must be the name of the keyword argument as a Ruby symbol. One of the nice things about keyword arguments is that you never have to remember what order the arguments need to be specified in.

Upvotes: 6

Related Questions