Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active January 11, 2024 23:52
Show Gist options
  • Save havenwood/0287e216efdce2997f8dbc978b0426d8 to your computer and use it in GitHub Desktop.
Save havenwood/0287e216efdce2997f8dbc978b0426d8 to your computer and use it in GitHub Desktop.
An anonymous Struct in pure Ruby (hoping Ruby adds a real one)
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