Search code examples
smalltalkgnu-smalltalk

Smalltalk - iterate over a dict array with conditions


I'm working on a Smalltalk small method, I want this method to iterate over a dictionary array and to return True or False depend on the conditions.

The dictionary array is an instance variable, name dictArray.

It looks like: [{'name': toto, 'age': 12}, {'name': tata, 'age': 25}]

So I want to iterate over dictArray and verify for each item the name and the age. If it matches I return true else false and the end of the iteration.

In python it should look like:

for item in dictArray:
    if item['name'] == aName and item['age'] == aAge:
        return True
return False

I can't find documentation with this special case (array iteration + condition + return)

Hope someone can help me!


Solution

  • To test whether a Collection contains an element that matches a condition, use anySatisfy:. It answers true iff there is a matching element.

    dictArray anySatisfy: [:each | (each at: 'name') = aName and: [(each at: 'age') = anAge]]
    

    Reference: https://www.gnu.org/software/smalltalk/manual-base/html_node/Iterable_002denumeration.html

    The way described above is the preferred way to write it. The following is only for explanation how it relates to your Python code example.

    anySatisfy: can be implemented in terms of do:

    anySatisfy: aBlock
       self do: [:each | (aBlock value: each) ifTrue: [^ true]].
       ^ false
    

    Or spelled out with your condition:

    dictArray do:
       [:each |
       ((each at: 'name') = aName and: [(each at: 'age') = anAge])
          ifTrue: [^ true]].
    ^ false
    

    This is the equivalent of your Python code.