(More) helpful run-time error messages

I love Ruby, but the run-time error messages could be more helpful. An example: I have an array in 3 levels, and use map to transform the inner elements. Basically something like
ary=[1,2,3] # but actually 3 levels
new_ary = ary.map { |n| n*fact }
resulting in the error message
TypeError (Array can't be coerced into Integer)
Because of the somewhat convoluted array structure I thought there was something wrong with the way I accessed the inner elements of ary. I struggled to find the error, until it dawned upon me that fact, coming from an external call, was an array and not a scalar. This would have been evident if the error message had included the name of the offending variable, like
TypeError (Array fact can't be coerced into Integer)
I would suppose that the name is available to the interpreter?

I’m not sure. The * operator would just get the values, and then it realises it has an Array not an Integer. You might need some kind of debugger to back out of that: ‘fact’ may not be a variable name, but a method call, or any arbitrarily complicated expression.

In irb and from command line, ruby does point me to the line and statement that the error comes up on:

Traceback (most recent call last):
	3: from test.rb:3:in `<main>'
	2: from test.rb:3:in `map'
	1: from test.rb:3:in `block in <main>'
test.rb:3:in `*': Array can't be coerced into Integer (TypeError)

So I can see where the problem lies. Usually I end up putting print statements around that, to see if things are what I expect…

(I’m often tripping over problems like this with dynamic languages. They can be big time sinks in debugging.)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs