In Ruby, keyword arguments in index refers to the practice of passing a keyword as an argument to an array, particularly when accessing or modifying elements within an array.
project_details = { status: "ongoing" }
projects = []
def projects.[]=(*args, **keyword_args)
puts "args: #{args}"
puts "keyword_args: #{keyword_args}"
end
Before ruby 3.3
keyword arguments were treated as positional arguments.
projects[1, status: "completed"], _ = ["Project A updated", "Project B"]
=> args: [1, {:status=>"completed"}, "Project A updated"]
=> keyword_args: {}
projects[2, **project_details], _ = [{budget: 10000}, "Project C"]
=> args: [2, {:status=>"ongoing"}, {:budget=>10000}]
=> keyword_args: {}
In ruby 3.3
Use of keyword arguments in multiple assignment is broken in 3.3
projects[1, status: "completed"], _ = ["Project A updated", "Project B"]
=> It crashes (BUG Segmentation fault)
# This leads to a segmentation fault because the method arr.[]= expects a hash for keyword arguments, but it receives a symbol (a) and an integer (1) instead.
projects[2, **project_details], _ = [{budget: 10000}, "Project C"]
# This passes the RHS argument as keywords to the method, treating keyword splat as positional argument
=> args: [2, {:status=>"ongoing"}]
=> keyword_args: {:budget=>10000}
In ruby 3.4
Passing keyword arguments in index to an array set methods is no longer allowed
and it throws SyntaxError
.
projects[1, status: "completed"], _ = ["Project A updated", "Project B"]
=> keyword arg given in index (SyntaxError)
projects[2, **project_details], _ = [{budget: 10000}, "Project C"]
=> keyword arg given in index (SyntaxError)