From: Paul Lutus Date: 2006-12-02T05:35:08+09:00 Subject: Re: Simple iteration in a function problem Blake Miller wrote: > >> I tried setting a variable like : >> def getXById(id) >> inst = X.new >> @ys.each_with_index do |comp, index| >> if( @ys[index].getUniqueId == id ) >> inst = @ys.fetch(index) >> end >> end >> >> inst >> end >> >> ...but I'm not looking to instantiate a new X, and even that solution >> seems to screw up the @ys array. > > I've also tried this: > def getXById(id) > matchingIndx = 0 > @components.each_index do |index| > if( @components[index].getUniqueId == uniqueId ) > matchingIndx = index > end > end > > @components.fetch(matchingIndx) > end > > but it just returns the 0th one every time (I'm assuming there wasn't a > match) You believe you are solving a specific programming problem, but in fact you are learning how to solve programming problems. 1. Put in as many message-printing lines into your program as you need to find out what is going on. 2. Keep adding debugging lines until the problem becomes obvious. 3. Repeat as required. When you look at a line of code like this: @components.each_index do |index| > if( @components[index].getUniqueId == uniqueId ) > matchingIndx = index > end > end And it doesn't deliver, what should you do? You should add lines that print helpful messages until it is impossible not to see the problem. First question. Is the ID in the array? Find out by printing all the array's IDs and look at them. Is it there? Second question. Does the variable "uniqueId" actually contain the required ID? Find out by printing its value. It is right? Third question. Can the comparison you are using actually produce the result you seek? Find out by testing it with two variables that actually are equal. Most difficult programming problems are beaten to death in just this way. The important things to remember are (1) the computer is breathtakingly dumb, (2) you are smarter than the computer, but (3) successful debugging requires you to think like the computer, as demeaning as that might seem at first. -- Paul Lutus http://www.arachnoid.com