One of the new features of Ruby 2.0 is keyword arguments. keyword arguments make it easier create method that take optional named arguments.
keyword arguments in the method definition must be symbols given in the new-style hash syntax.
Assume we have a method:
1 2 3 4 5 6 7 8 9 |
|
Ruby 2.0 blocks can also be defined with keyword arguments:
1 2 3 4 5 6 7 8 9 |
|
Keyword arguments vs Positional arguments
Assume we have a method with positional arguments:
1 2 3 4 5 |
|
This method does its job, but as a reader of the code using the total method, I have no idea what those arguments mean without looking up the implementation of the method.
By using keyword arguments, we know what the arguments mean without looking up the implementation of the called method:
1 2 3 4 5 6 7 |
|
Keyword arguments allow us to switch the order of the arguments, without affecting the behavior of the method:
1 2 3 |
|