Project

General

Profile

Feature #16806

Struct#initialize accepts keyword arguments too by default

Added by k0kubun (Takashi Kokubun) 4 months ago. Updated 4 months ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:98014]

Description

Proposal

Post = Struct.new(:id, :name)

# In addition to this,
Post.new(1, "hello") #=> #<struct Post id=1, name="hello">

# Let the following initialization also work
Post.new(id: 1, name: "hello") #=> #<struct Post id=1, name="hello">

Known incompatibility

  • Post.new(id: 1, name: "hello") will be #<struct Post id=1, name="hello"> instead of #<struct Post id={:id=>1, :name=>"hello"}, name=nil>
    • Struct initialization only using keyword arguments should be warned in Ruby 3.0. This feature should be introduced in Ruby 3.1 or later.

Edge cases

  • When keyword arguments and positional arguments are mixed: Post.new(1, name: "hello")
    • This should continue to work like Ruby 2: #<struct Post id=1, name={:name="hello"}>
  • Only keywords are given but they include an invalid member: Post.new(foo: "bar")
    • ArgumentError (unknown keywords: foo)
  • When keyword_init is used
    • nil: default behavior. Positional arguments given use positional init. Keyword arguments without positional arguments treated as positional in 3.0 with warning, and treated as keyword init in Ruby 3.1.
    • true: Require keyword init, disallow positional init.
    • false: Treat keywords as positional hash.

Use cases


Related issues

Related to Ruby master - Feature #11925: Struct construction with kwargsClosedActions

Also available in: Atom PDF