From: Thomas Sawyer Date: 2011-11-24T08:33:21+09:00 Subject: [ruby-core:41267] [ruby-trunk - Feature #4862] Struct#to_hash Issue #4862 has been updated by Thomas Sawyer. Despite it's implementation, I thought Struct was intended to provide a convenient way to make quick classes. Which is why I assume it would have instance variables. I can understand though that it would be implemented in another fashion for speed. But I would still think the public interface to appear as if it were a typical sort of class. Given it's current interface it hardly resembles a Hash at all. I think #each at least should act the same as a Hash if #to_hash would be added to it, but instead it acts like an Array: >> s = Struct.new(:a, :b).new(1,2) => # >> s.map{ |a| a } => [1, 2] > "because there is no #to_h (but indeed it is somewhat inconsistent with #to_i, #to_int, ...)" Not just "somewhat". So I ignore all that heehawing and define #to_h wherever it makes sense when I need it. Why #to_h should be carved out as some odd exception seems to me just a lot of needless fuss over... what? ---------------------------------------- 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