Jepthe Tan
Jepthe Tan

Reputation: 85

Smalltalk array manipulaton

I am new in using smalltalk and i am trying to iterate an array inside an array and evaluate each array member if it is divisible by 4 if true it will return the byte array containing the element using select method Here's my code:

| anArray result |
anArray := #(#(1 2 3 3 4 6 7) #(6 7 6 9 9 4 7 6) #(11 12 13 14 15 14)).
anArray select: [ :each | 
     each do: [ :ea | 
         ea \\ 4 == 0 ifTrue: [ Transcript show: each printString ]
     ]
]

The problem is that it needs a boolean condition in the select method. Do you know other ways to use select method to return the said output?

Thanks!

Upvotes: 3

Views: 362

Answers (2)

Leandro Caniglia
Leandro Caniglia

Reputation: 14843

(Read James Foster's answer first)

If you want to select and print:

anArray select: [:eachArray | 
  (eachArray anySatisfy: [:eachElement | eachElement \\ 4 == 0])
      ifTrue: [Transcript cr; show: eachArray];    "no need to #printString"
      yourself]

which forces the Boolean resulting from #anySatisfy: to be answered by the block.

Upvotes: 3

James Foster
James Foster

Reputation: 2210

Welcome to Smalltalk! Your question is a bit ambiguous. Do you want to select each inner array where any element is divisible by 4? If so, try the following:

| anArray result |
anArray := #(#(1 2 3 3 4 6 7) #(6 7 6 9 9 4 7 6) #(11 12 13 14 15 14)).
anArray select: [ :eachArray | 
    eachArray anySatisfy: [ :eachElement | 
        eachElement \\ 4 == 0.
    ].
].

Or do you want to print each element from the inner array that is divisible by 4? If so, try the following:

| anArray result |
anArray := #(#(1 2 3 3 4 6 7) #(6 7 6 9 9 4 7 6) #(11 12 13 14 15 14)).
anArray do: [ :eachArray | 
    eachArray do: [ :eachElement |
        eachElement \\ 4 == 0 ifTrue: [
            Transcript cr; show: eachElement.
        ].
    ].
].

Upvotes: 5

Related Questions