Skip to content

Instantly share code, notes, and snippets.

@pmn4
Created January 14, 2021 14:25
Show Gist options
  • Save pmn4/01442e7dec706292ebe25577f6d0fe03 to your computer and use it in GitHub Desktop.
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
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
@pmn4
Copy link
Author

pmn4 commented Jan 14, 2021

> KS = KwargsStruct.new(:a, :b, :c)
=> KS

# kwargs-only
> KS.new(a: 1, c: 3)
=> #<struct KS a=1, b=nil, c=3>

# combined args and kwargs
> ks = KS.new(2, 5, c: 3)
=> #<struct KS a=2, b=5, c=3>

# combined args and kwargs, with keyword priority
> ks = KS.new(2, a: 1, c: 3)
=> #<struct KS a=1, b=nil, c=3>

@pmn4
Copy link
Author

pmn4 commented Jan 14, 2021

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