Parámetros con Nombre. Named Parameters in Ruby 2.0

In computer programming, named parameters or keyword arguments refer to a computer language’s support for function calls that clearly state the name of each parameter within the function call itself.

Ruby 2.0 admite parámetros con nombre.

def foo(bar: '12345', baz: 'abcdef')
  [bar, baz]
foo                         # => ["12345", "abcdefg"]
foo(bar: 'bar')             # => ["bar", "abcdef"]
foo(bar: 'bar', baz: 'baz') # => ["bar", "baz"]

[2] pry(main)> require './named_parameters2'
["12345", "abcdef"]
["bar", "abcdef"]
["bar", "baz"]
=> true
Si se llama con un nombre no declarado se produce un ArgumentError:
[3] pry(main)> foo(chuchu: 'chuchu')
ArgumentError: unknown keyword: chuchu
from (pry):3:in `__pry__'
Also, you can combine them with regular parameters.

def foo(value, bar: '12345', baz: 'abcdef')
  [value, bar, baz]
foo('VALUE')                         # => ["VALUE", "12345", "abcdefg"]
foo('VALUE', bar: 'bar')             # => ["VALUE", "bar", "abcdef"]
foo('VALUE', bar: 'bar', baz: 'baz') # => ["VALUE", "bar", "baz"]

Se pueden combinar con splats:

[~/rubytesting/TheRubyProgrammingLanguage/Chapter6MethodsProcsLambdasAndClosures]$ cat named_parameters4.rb 
require 'pp'

def cycle(first_value, *values, name: 'default')
  return [ first_value, values, name]

pp cycle(1, 2, 3, 4, name: 'Pedro') # [1, [2, 3, 4], "Pedro"]

You can stop an ArgumentError being raised and deal with arbitrary keyword arguments by using a double-splat (double asterisk) to capture all keywords not already assigned and puts them in a hash:

[~/rubytesting/TheRubyProgrammingLanguage/Chapter6MethodsProcsLambdasAndClosures]$ cat named_parameters5.rb 
require 'pp'

def foo(bar: '12345', baz: 'abcdef', **rest)
  [bar, baz, rest]
pp foo(bar: 'bar', chuchu: 'chuchu', chachi: 'chachi') # ["bar", "abcdef", {:chuchu=>"chuchu", :chachi=>"chachi"}]

Skipping the default value. Required keyword arguments in Ruby 2.1

Ruby 2.1 introduces required keyword arguments. You can use required argument by skipping the default value.

You’ll get a ArgumentError if you don’t supply the argument:

def exclaim(text, exclamation: '!', number:)
  text + exclamation * number

exclaim('Yo', number: 5) # => 'Yo!!!!!'
exclaim('Yo') # raises: ArgumentError: missing keyword: number


  1. Véase Ruby 2.0 - Getting Started and Named Parameters (YouTube)
  2. Keyword Arguments in Ruby 2.0 por Chris Zetter

Casiano Rodriguez León 2015-06-18