iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
💎

Ruby 3.2 - Keyword Parameters Part 1 and 2

に公開
2022/12/06

This is the article for Day 1 of the Ruby 3.2 Advent Calendar.

https://qiita.com/advent-calendar/2022/ruby32

Ruby's version is updated every year on Christmas. If all goes well, Ruby 3.2 should be released on December 25th this year.
Let's wait for the release while looking at the changes little by little every day until 3.2 is released.

The source is NEWS.md for Ruby 3.2 preview3.


Keyword Parameters Part 1

Feature #18351: Support anonymous rest and keyword rest argument forwarding - Ruby master - Ruby Issue Tracking System

It is no longer necessary to assign variable names when using parameters received via * or ** as arguments.

def hoge(a, *, **)
  a  #=> 123
  fuga(*, **)
end

def fuga(*args, **opts)
  pp args, opts
  #=> [456]
  #   {:x=>"abc", :y=>"def"}
end

hoge(123, 456, x: 'abc', y: 'def')

However, this causes an error if there are keyword parameters.

def hoge(a, *, x: nil, **)
  fuga(*, **)   #=> no anonymous keyword rest parameter
end

Apparently, this was a bug. It seems it will likely be fixed by the time 3.2 is released.
Bug #19132: ** を引数に指定すると no anonymous keyword rest parameter になる - Ruby master - Ruby Issue Tracking System

Keyword Parameters Part 2

Bug #18633: proc { |a, **kw| a } autosplats and treats empty kwargs specially - Ruby master - Ruby Issue Tracking System

The behavior when passing an array has changed when block parameters include keyword parameters.
Up to 3.1, the elements in the array were expanded and assigned to parameters (autosplatting), but in 3.2, it remains as an array.

Ruby 3.1:

proc{|a| p a}.call([1, 2])         #=> [1, 2]
proc{|a,| p a}.call([1, 2])        #=> 1
proc{|a, k:nil| p a}.call([1, 2])  #=> 1
proc{|a, **k| p a}.call([1, 2])    #=> 1

Ruby 3.2:

proc{|a| p a}.call([1, 2])         #=> [1, 2]
proc{|a,| p a}.call([1, 2])        #=> 1
proc{|a, k:nil| p a}.call([1, 2])  #=> [1, 2]
proc{|a, **k| p a}.call([1, 2])    #=> [1, 2]

Discussion