Reputation: 799
I am a newbie on Smalltalk,after I did study overall the topics and I thought I was ready to start to my project but when I started I just got stucked in doing nested for loops at the very beginning.I did search for this issiue but the examples on the internet didn't meet my needs which are simple,I just want to get the indices of the loops to use them. Maybe this topic would help me and upcoming starters so thank you behalf of me and them:)
I don't know if this is very easy to find or doable but I tried to do
1 to: 25 do: [[:a |1 to: 80 do: [:b | a , b printString ,' '],cr]].
I just want to concatenate the numbers as
11 12 13 14 ..180
21 22 23 ...
.
.
251 252 ... 2580
to use them as indices or pointers and then store it in a dictionary. But I just couldn't do the nested loop and at least write them with print.
I use Pharo 3.0 if you want to know.
Upvotes: 2
Views: 2096
Reputation: 9382
A Squeakish/Pharoish way to cumulate into a single collection from nested loops is to use an intermediate Stream, like with this snippet:
String streamContents: [:aStream |
1 to: 25 do: [:a |
1 to: 80 do: [:b |
aStream
print: a;
print: b;
space]]].
Or if you want to create an Array of Number:
Array new: 25*80 streamContents: [:aStream |
1 to: 25 do: [:a |
1 to: 80 do: [:b |
aStream nextPut: (a printString , b printString) asNumber]]].
Upvotes: 1
Reputation: 5125
You're code works fine (except for the missing #printString
message to a
and the wrong nesting of the blocks) but as @MartinW says, you're not using the return value of the block. What you can do instead (to keep as much of your current code as possible) is this (I like to code in a more explicit way):
Transcript open.
1 to: 25 do: [ :a |
1 to: 80 do: [ :b |
Transcript
show: a printString;
show: b printString;
show: ' ' ].
Transcript cr ].
Upvotes: 4
Reputation: 5041
I am not sure if there is a better way than converting to strings. But if you want to go that route try printing or inspecting in a workspace:
((1 to: 25) collect: [ :a | (1 to: 80) collect: [ :b | a printString , b printString ]]) flattened.
With do: aBlock
you evaluate aBlock for each element in the receiver, but with
collect: aBlock
you collect the result of each block evaluation in a new collection.
Depending on what you intend to do, you might have to convert the resulting strings back to numbers.
Upvotes: 2