I got a semestral project to do in Smalltalk, but I got stuck in choosing a random element from an array.
array = #('Alex' 'Bob' 'Frank' 'Samantha').
^"RandomChoice"
And now I need to pick a random name from the array. I found Random function, but don't know how it works. Anyone help? Thanks!
First of all it is written Smalltalk and not SmallTalk.
You need to think about what you are trying to achive. Since you did not specify your Smalltalk, I'll be using the one I know the most the Smalltalk/X-jv branch.
Your comment shows that you have found the
atRandommethod which should work as you have specified in your question:I have tried it on Smalltalk/X and it works as expected.
Even with your when executed at Workspace it works correctly:
#('Alex' 'Bob' 'Frank' 'Samantha') atRandom.'Frank'('Frank'is the result of theprint it)You could do it differently, like (this is suboptimal as
atRandomworks correctly):(#('Alex' 'Bob' 'Frank' 'Samantha') asOrderedColletion randomShuffle) at: 1.This makes OrderedCollection from Array and shuffles it randomly and picks first position.
Your method would could look like this: