Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An anonymous Struct in pure Ruby (looking forward to real ones in Ruby 3)
module ToStruct
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 ToStruct
struct = ~{aim: true, tip: 'broadhead'}
pp struct
#>> #<struct aim=true, tip="broadhead">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.