| Start |
|---|
| Using arbitrary keyword arguments with splat operator You can define a method to accept an arbitrary number of keyword arguments using the double splat ( The arguments are captured in a Using a the splat operator with keyword arguments will prevent keyword argument validation, the method will never raise an As for the standard splat operator, you can re-convert a This is generally used when you need to manipulate incoming arguments, and pass them to an underlying method: |
| Using keyword arguments You define a keyword argument in a method by specifying the name in the method definition: You can define multiple keyword arguments, the definition order is irrelevant: Keyword arguments can be mixed with positional arguments: Mixing keyword argument with positional argument was a very common approach before Ruby 2.1, because it was not possible to define required keyword arguments (opens new window). Moreover, in Ruby < 2.0, it was very common to add an Note that trying to pass a not-defined keyword argument will result in an error: |
| Required keyword arguments Required keyword arguments were introduced in Ruby 2.1, as an improvement to keyword arguments. To define a keyword argument as required, simply declare the argument without a default value. You can also mix required and non-required keyword arguments: RemarksKeyword arguments were introduced in Ruby 2.0, and improved in Ruby 2.1 with the addition of required keyword arguments. A simple method with a keyword argument looks like the following one: As a reminder, the same method without keyword argument would have been: You can simulate keyword argument in previous Ruby versions using a Hash parameter. This is still a very common practice, especially in libraries that provides compatibility with pre-2.0 Ruby versions: |
Read Article
https://develop.horje.com/learn/1434/reference