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).
I know the question is about ruby 1.9.3, but starting from ruby 2.0.0, Struct
has a to_h
method which does the job.
MyMeaningfulName = Struct.new(:alpha, :beta, :gamma)
my_var = MyMeaningfulName.new
my_var.to_h # -> { :alpha=>nil, :beta=>nil, :gamma=>nil }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With