Robert Klemme
3/10/2007 10:44:00 AM
On 10.03.2007 10:36, Sharon Phillips wrote:
> On 10/03/2007, at 7:29 PM, Aaron Smith wrote:
>
>> I need to use an OpenStruct to mimic what an object acts like in another
>> language. is it possible somehow to find what keys are set on an
>> OpenStruct at any given time?
>
> Disclaimer: I'm fairly new to this, so there's a reasonable chance I'm
> wrong to some degree.
>
> Internally, OpenStruct stores the keys as symbols in a hash in an array
> @table which can be accessed via marshal_dump.
>
> Alternatively, you may like to add a method like keys_added:
>
> require 'ostruct'
>
> class OpenStruct
> def keys_added
> @table.keys.map{|k| k.to_s}
> end
> end
>
> person= OpenStruct.new
> person.name= "Fred"
> person.age= 100
>
> person.keys_added
> => ["age", "name"]
Yeah, there doesn't seem to be a public method for this. An alternative
approach (btw, I'd stick with symbols as they are more efficient):
irb(main):010:0> o=OpenStruct.new
=> #<OpenStruct>
irb(main):011:0> o.foo=1
=> 1
irb(main):012:0> o.bar=2
=> 2
irb(main):013:0> o.instance_variable_get("@table").keys
=> [:bar, :foo]
OTOH, if you frequently need to get the list of defined members a Hash
is probably a better choice.
Kind regards
robert