Ruby Shoes calculator functions don't run (array related error?)

263 Views Asked by At

I tried to code a simple calculator with GUI in Ruby Shoes.

The idea was to save the numbers on the buttons you press in an array and then get an integer from that (loop that adds array[i] * {arraydepth} to the number). Then I would clear the stack that holds my "result" display and replace it with a new textfield that shows the result (currently it just says "changed" as I didn't get that far yet.)

My methods don't work. When I try to add a number to my array with this function

def addToVar(number)

  if choosingVar2
    var2Counter += 1
    var2[var2Counter] = number
  else
    var1Counter += 1
    var1[var1Counter] = number
  end

  transToNumber

rescue
  @p.clear { para \"edited\" }

end

it doesn't execute any of the code before the rescue. I tried to put an alert("alert") before the if/else stuff. That worked, but everything after the first if and before the rescue isn't executed. Why?

I get the same problem when I try to get an integer from the values stored in the array with the following function

def transToNumber

  mult = 1
  while var1Counter > 0
    var1Num += var1[var1Counter] * mult
    mult *= 10
    var1Counter -= 1
  end

  mult = 1
  while var2Counter > 0
    var2Num += var2[var2Counter] * mult
    mult *= 10
    var2Counter -=1
  end

  @p.clear { para \"edited\" }

end

I suspect I'm doing something wrong with the array.

Complete code here.

1

There are 1 best solutions below

2
On

The problem you're having deals with variable scope. All of the variables defined at the top of your code (e.g., choosingVar2) are local and are not visible to your methods like addToVar(number). Ruby is throwing an error about this, but you are not seeing any helpful error messages because of the generic rescue statement, which is catching but not reporting exceptions. This is why it looks like the code is not executing.

First thing I would do is either comment out the rescue statements you have or make them display a generic message so you can debug more easily:

rescue Exception => msg
    puts msg

Second, you can simply make all of your initial variables instance variables, which will make them accessible in your methods (within the scope of what I assume is a class/object in Shoes):

@var2 = []
@var2[0] = 0
@var2Counter = 0
@var2Num = 0

@choosingVar2 = false

def addToVar(number)
  if @choosingVar2 
        @var2Counter += 1
        @var2[@var2Counter] = number
...

For more about variable scope you can find lots of tutorials and good write-ups online (or in ruby docs themselves). Here is one example: http://zetcode.com/lang/rubytutorial/variables/