From: Aaron Smith Date: 2007-03-13T04:59:44+09:00 Subject: Re: OpenStruct,, know what keys are set 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.. 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/.