Search code examples
smalltalkpharo

Smalltallk - How can I get an Array (or Collection) of the all the Instance variables in an Object (the current Instance) of a Class?


Let's say we have a Class and we instantiate it, creating an Instance of that Class. This Instance has a number of (instance)variables, defined by the class, that I need to use. I'd like to get all these (instance)variables in an Array or some Collection so I can iterate through them and set them to some value, not nil.

How can I do this?


Solution

  • You can send #allInstVarNames to a class (Behavior) to get names of all instance variables defined by it and by superclasses. If you need without superclass variables, you can use #instVarNames

    Let's say that var is your variable that you need to work with. Then you can get the collection of instance variable names and iterate them.

    You can use #instVarNamed:put: to set instance variable by name, and #instVarNamed: to get the value by name (in case you need).

    I think that something like this may help you:

    var class allInstVarNames do: [ :instVarName |
      var instVarNamed: instVarName put: <yourValue>