From: Sharon Phillips Date: 2007-03-13T07:46:08+09:00 Subject: Re: OpenStruct,, know what keys are set On 13/03/2007, at 6:59 AM, Aaron Smith wrote: > Jan Friedrich wrote: >> o = OpenStruct.new >> o.foo = 2 >> o.bar = 4 >> o.marshal_dump # => {:foo=>2, :bar=>4} >> o.marshal_dump.keys # => [:foo, :bar] >> >> regards, >> Jan > > nice one, that's faster.. marshal_dump returns @table, so marshal_dump.keys == @table.keys except that @table is not accessable from outside OpenStruct. http://www.ruby-doc.org/stdlib/libdoc/ostruct/rdoc/classes/ OpenStruct.html Click on the [Source] link to see the code behind these methods. Note that some of your examples here return symbols (2 and 5) whilst 3 and 4 take an extra step of transforming these into strings. Looks like you're having fun :) Dave > require 'ostruct' > require 'benchmark' > > class OpenStruct > def keys_added > @table.keys.map{|k| k.to_s} > end > end > > lady = OpenStruct.new > 0.upto(10) do |i| > eval("lady.cat#{i} = i") > #puts eval("lady.cat#{i}") > end > > Benchmark.bm do |x| > x.report("Find all keys 1"){ > 0.upto(100000) do > lady.methods(false).grep(/[^=]$/) > end > } > > x.report("Find all keys 2"){ > 0.upto(100000) do > lady.instance_variable_get("@table").keys > end > } > > x.report("Find all keys 3"){ > 0.upto(100000) do > lady.keys_added > end > } > > > x.report("Find all keys 4"){ > 0.upto(100000) do > lady.instance_variable_get("@table").keys.map{|k| k.to_s } > end > } > > x.report("Find all keys 5"){ > 0.upto(100000) do > lady.marshal_dump.keys > end > } > end > > user system total real > Find all keys 1 4.110000 0.010000 4.120000 ( 4.151098) > Find all keys 2 0.160000 0.000000 0.160000 ( 0.153028) > Find all keys 3 0.870000 0.010000 0.880000 ( 0.884275) > Find all keys 4 0.900000 0.000000 0.900000 ( 0.897666) > Find all keys 5 0.130000 0.000000 0.130000 ( 0.137231) > > -- > Posted via http://www.ruby-forum.com/. >