I’m using a Struct as opposed to a simple Hash in a project to provide a semantic name to a collection of key value pairs. Once I’ve built the structure, however, I need to output a hash value. I’m in Ruby 1.9.3. Example:
MyMeaninfulName = Struct.new(:alpha, :beta, :gamma) do
def to_hash
self.members.inject({}) {|h,m| h[m] = self[m]; h}
end
end
my_var = MyMeaningfulName.new
my_var.to_hash # -> { :alpha=>nil, :beta=>nil, :gamma=>nil }
Is there a reason why Struct does not include a to_hash method? It seems like a natural fit, but perhaps there’s an underlying reason why it’s not included.
Second, is there a more elegant way to build a generic to_hash method into Struct (either generally, via monkeypatching, or through a module or inheritance).
Try this: