Issue #4862 has been updated by Benoit Daloze.


Thomas Sawyer wrote:
> Then again maybe I'm wrong b/c I was just surprised by the fact that a Struct doesn't have (or at least act like it has) instance_variables.
> 
>   Struct.new(:a).new(1).instance_variables  #=> []

Yeah, it is implemented with an array stored in the RStruct struct in MRI.

> A Struct#to_hash method would be very useful in this situation.

I agree.

#to_hash is the right method name because there is no #to_h (but indeed it is somewhat inconsistent with #to_i, #to_int, ...)

----------------------------------------
Feature #4862: Struct#to_hash
http://redmine.ruby-lang.org/issues/4862

Author: Hal Brodigan
Status: Open
Priority: Normal
Assignee: 
Category: 
Target version: 


Occasionally, it is necessary to convert a Struct to a Hash (especially when generating JSON from an Array of Structs). A Struct#to_hash method would be very useful in this situation.

    class Struct

      #
      # Returns the Hash representation of the members and values within the struct.
      #
      def to_hash
        new_hash = {}

        each_pair do |member,value|
          new_hash[member] = value
        end

        new_hash
      end

    end


-- 
http://redmine.ruby-lang.org