Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default Value vs. Keyword Argument

Tags:

ruby

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

like image 934
Helio Ha Avatar asked Apr 02 '16 01:04

Helio Ha


2 Answers

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.

like image 185
David Grayson Avatar answered Sep 21 '22 16:09

David Grayson


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.

like image 24
Incerteza Avatar answered Sep 22 '22 16:09

Incerteza