[Newbies] Referencing a variable?

Amir Ansari fractallyte at csi.com
Thu Dec 3 11:59:38 UTC 2009


Dear list

I've been looking through books, blogs and lists for a solution to this 
problem, but can't find anything!  Which means that I'm not thinking 
about it in the right way...  I'd be very grateful if someone could 
enlighten me!


I have myLibrary (an OrderedCollection) of Books (class with 'title' 
and 'author' instance variables):

myLibrary := OrderedCollection new.
myLibrary
	add: (Book new
		title: 'Hamlet';
		author: 'Shakespeare');
	add: (Book new
		title: 'The Hobbit';
		author: 'Tolkien');
	add: (Book new
		title: 'Ben Hur';
		author: 'Wallace').


Now, if I want to gather all the titles and authors into new 
collections, I can do the following:

titles := myLibrary collect: [:each | each title].
authors := myLibrary collect: [:each | each author].


But I'd like to reuse the code as much as possible, so I'd prefer to do 
something like this:

element := 'title'.
choice := myLibrary collect: [:each | each element].

So I'm trying to refer to the instance variables 'title' or 'author' 
using another variable called 'element'.  But it doesn't work, and I 
can't figure out another way to do it...

Is there another solution?

Thanks!



More information about the Beginners mailing list