iTranslated by AI
Ruby 3.2 - Keyword Parameters Part 1 and 2
This is the article for Day 1 of the Ruby 3.2 Advent Calendar.
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
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
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