From: ruby@... Date: 2016-10-25T18:37:46+00:00 Subject: [ruby-core:77760] [Ruby trunk Feature#11925] Struct construction with kwargs Issue #11925 has been updated by Herwin W. https://github.com/ruby/ruby/pull/1468 A proposal for an implementation. ~~~ ruby irb(main):001:0> MyClass = Struct.new(:a, :b, :c) => MyClass irb(main):002:0> MyClass.new_from_kwargs(a:1, c: 3) => #<struct MyClass a=1, b=nil, c=3> irb(main):003:0> MyClass.new_from_kwargs(1, 2, 3, b: 3) => #<struct MyClass a=1, b=3, c=3> irb(main):004:0> MyClass.new_from_kwargs(d: 4) NameError: no member 'd' in struct from (irb):4:in `new_from_kwargs' from (irb):4 from ./irb:11:in `<main>' irb(main):005:0> MyClass.new_from_kwargs(1, 2, 4, 5, b: 3) IndexError: offset 3 too large for struct(size:3) from (irb):5:in `new_from_kwargs' from (irb):5 from ./irb:11:in `<main>' irb(main):006:0> ~~~ ---------------------------------------- Feature #11925: Struct construction with kwargs https://bugs.ruby-lang.org/issues/11925#change-61066 * Author: Ilya Vorontsov * Status: Open * Priority: Normal * Assignee: ---------------------------------------- Propose to make Struct subclass constructors which accept keyword arguments. Not sure, if it's reasonable to allow `.new` accept kwargs, so may be should use different method named like `.create`: ```ruby Point = Struct.new(:x,:y, :color) pt_1 = Point.create(x: 1, y: 2) # => Point<x: 1, y: 2, color: nil> pt_2 = Point.create!(x: 1, y: 2) # => ArgumentError, color not specified. ``` It will greatly simplify work with big structures, especially in cases when struct layout changes and for cases when structure can have lots of non-significant values. It also allows simpler ways to use implement default values for struct members. -- https://bugs.ruby-lang.org/ Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe> <http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>