Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active January 9, 2025 16:30
Show Gist options
  • Select an option

  • Save havenwood/0287e216efdce2997f8dbc978b0426d8 to your computer and use it in GitHub Desktop.

Select an option

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
unless Object.const_defined?(class_name)
Object.const_set(class_name, Struct.new(*keys))
end
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