Last active
January 11, 2024 23:52
-
-
Save havenwood/0287e216efdce2997f8dbc978b0426d8 to your computer and use it in GitHub Desktop.
An anonymous Struct in pure Ruby (hoping Ruby adds a real one)
This file contains 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
module StructLiteral | |
refine Hash do | |
def to_struct(class_name = nil) | |
if class_name | |
Object.const_set(class_name, Struct.new(*keys)) | |
Object.const_get(class_name).new(*values) | |
else | |
Struct.new(*keys).new(*values) | |
end | |
end | |
alias ~@ to_struct | |
end | |
end | |
using StructLiteral | |
~{aim: true, tip: :broadhead} | |
#=> #<struct aim=true, tip="broadhead"> | |
{aim: true, tip: :broadhead}.to_struct(:Arrow) | |
#=> #<struct Arrow aim=true, tip=:broadhead> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment