From: "marcandre (Marc-Andre Lafortune)" Date: 2012-03-26T08:33:16+09:00 Subject: [ruby-core:43671] [ruby-trunk - Feature #1400] Please add a method to enumerate fields in OpenStruct Issue #1400 has been updated by marcandre (Marc-Andre Lafortune). Hi, Peter Vandenabeele wrote: > Is there a specified order for the enumeration? (I presume not, but > curious). As the implementation uses a hash, it would be the same order, i.e. order in which they were set. Thomas Sawyer wrote: > If #each_pair, why not #each? The nice thing about `each_pair` is that is common to both Hash and Struct and would have the same meaning for OpenStruct. `Struct#each` yields only the values, so that might cause some confusion? > It was also recommended to me to suggest #to_h here. I think it would be nice to have this, and not only in OpenStruct. Matz seems positive about it too [ruby-core:43363]. Here's what I have so far: https://github.com/marcandre/ruby/compare/ostruct ---------------------------------------- Feature #1400: Please add a method to enumerate fields in OpenStruct https://bugs.ruby-lang.org/issues/1400#change-25170 Author: tpo (Tomas Pospisek) Status: Assigned Priority: Normal Assignee: marcandre (Marc-Andre Lafortune) Category: lib Target version: 2.0.0 =begin There are two ways to find out what fields an OpenStruct instance has. One is through inspect, however that returns a String that needs to be parsed. The second is by white box engineering, looking at OpenStructs source code and seeing that in fact, it has a hash and getting the keys of that hash... The second way is faster, more robust, but will break once OpenStruct will be re-engineered... So I suggest to add an explicit method to return a list of fields in an OpenStruct instance: --- ostruct.rb.old 2009-04-23 15:26:45.000000000 +0200 +++ ostruct.rb 2009-04-23 15:32:41.000000000 +0200 @@ -110,6 +110,15 @@ @table.delete name.to_sym end + # + # Returns an Array containing the fields of an OpenStruct instance + # + # p record.fields # -> [:age, :pension, :name] + # + def fields + @table.keys + end + InspectKey = :__inspect_key__ # :nodoc: # =end -- http://bugs.ruby-lang.org/