Created
January 14, 2021 14:25
-
-
Save pmn4/01442e7dec706292ebe25577f6d0fe03 to your computer and use it in GitHub Desktop.
A Ruby Struct, but with a keyword argument constructor, allowing for optional parameters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class KwargsStruct < Struct | |
| def initialize(*args, **kwargs) | |
| # assumes the keyword argument takes priority | |
| super *members.each_with_index.map { |k, i| kwargs[k] || args[i] } | |
| end | |
| end |
nevermind, I just learned about Struct's keyword_init:
KS = Struct.new(:a, :b, :c, keyword_init: true)> KS.new(a: 1, c: 3)
=> #<struct KS a=1, b=nil, c=3>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.