Struct to Hash in Ruby

Sometimes I wonder why certain functions are missing, but Ruby’s nice and easy to fix if you feel it’s missing something. Quite often I use structs for data classes, and if I want to use DBI to insert them into the database then a hash makes that easier.

# encoding: utf-8

class Struct

  # Returns the values for this instance as a hash
  def to_h
    Hash[ self.members.zip(self.to_a) ]
end # Struct
Added on:
Last updated:
Info:- Ruby 1.9 - OSX 10.6.6