Anonymous Arguments Passing Improvements in Ruby 3.2
Ruby 3.2 introduces a new way to pass anonymous arguments, making it easier and cleaner to work with keyword arguments in your code.
Before Ruby 3.2
Before Ruby 3.2, the way to pass anonymous arguments was to use the **kwargs
syntax. This allowed you to pass any number of keyword arguments to a method, which could then be accessed as a hash within the method. However, this method had some limitations, such as the need to manually extract values from the hash and the lack of clarity when working with multiple keyword arguments.
Here is an example of how you would pass anonymous arguments prior to Ruby 3.2:
# before ruby 3.2
def create_request(url, from,
**kwargs)
puts "send to #{url}"
puts "from #{from}"
puts "using #{kwargs.fetch(:method, nil)}"
puts "with headers #{kwargs.fetch(:headers, nil)}"
puts "DEBUGGER TURNED ON" if kwargs.fetch(:debugger, false)
puts "debug:"
p kwargs
end
create_request('/myurl', 'local',
method: :get, headers: :none, debugger: true)
After Ruby 3.2
A new version introduces a new syntax for passing anonymous arguments. The new syntax allows you to unpack keyword arguments into a separate variable, making them more intuitive. Here is the same example as above, but using the new syntax in Ruby 3.2:
# after ruby 3.2
def create_request(*,
**)
x = [*]
url, from = [*]
y = {**}
puts "send to #{x.first} - as variable: #{url}"
puts "from #{x.last} - as variable #{from}"
puts "using #{y.dig(:method)}"
puts "with headers #{y.dig(:headers)}"
puts "DEBUGGER TURNED ON" if {**}.dig(:debugger) == true
puts "debug:"
p(*, **)
end
create_request('/myurl', 'local',
method: :get, headers: :none, debugger: true)
Conclusion
The new anonymous argument passing syntax in Ruby 3.2 provides a more intuitive and cleaner way to work with keyword arguments, making it easier to write both readable and maintainable code. Whether you're a seasoned Ruby developer or just starting, it's worth upgrading to Ruby 3.2 and taking advantage of these improvements.