Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to add to_hash (or to_h) method to Struct?

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).

like image 576
GSP Avatar asked Sep 06 '12 13:09

GSP


1 Answers

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 } 
like image 164
Geoffroy Avatar answered Oct 30 '22 22:10

Geoffroy