Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Ruby Struct utilities: use named parameters to create Struct-based objects and return JSON from Structs
# Struct utilities
# Author:: Matt Sullivan (
# Attempt to require Ruby Gems; 1.8.X gem support only
require 'rubygems'
rescue LoadError
# Ruby Gems not installed
require 'json'
# Extends Structs to support named parameter hashes
class NamedStruct < Struct
# Override the initialize constructor to handle hashes of named parameters
def initialize *args
return super unless (args.length == 1 and args.first.kind_of? Hash)
args.first.each_pair do |k, v|
# Keys get converted to symbols for consitency
# Structs in 1.9.x store their members as symbols, but in 1.8.7 and JRuby,
# they're stored as strings, so ensure you're comparing members as symbols
self[k.intern] = v if {|x| x.intern}.include? k.intern
# Extends NamedStructs to support Hash and JSON outputting
class JSONStruct < NamedStruct
# Converts a Struct to a hash
def to_hash
hash =
self.members.each { |m| hash[m] = self[m] }
# Converts a Struct to a JSON string
def to_json *args
to_hash.to_json *args

This comment has been minimized.

Copy link

rohitpaulk commented Sep 27, 2017

I found myself having to redeclare this in almost every project, so I created a gem:

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.