I use Struct instead of a simple Hash in the project to provide a semantic name for the collection of value pairs. However, when I built the structure, 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
Is there a reason why Struct does not include the to_hash method? This looks like a natural form, but perhaps there is a main reason why it is not included.
Secondly, is there a more elegant way to create a general to_hash method in Struct (usually through monkeypatching, and through module or inheritance).
source
share