Declaring variables?


(Philip Mak) #1

As I understand it, there isn’t really a concept of “declaring” a
variable in ruby. When I make an assignment to a variable, it’s
automatically created with the type of the rvalue if needed.

If I try to read a variable that doesn’t exist, I’ll get an exception.

But what if I try to set the wrong variable name? e.g.:

number = 3
numbr += 1 # a typo
puts number # prints 3, but should have printed 4

Is there a way to protect myself from typos on lvalue variable names?


(Albert) #2

no

···

On Monday 03 June 2002 06:34 pm, you wrote:

As I understand it, there isn’t really a concept of “declaring” a
variable in ruby. When I make an assignment to a variable, it’s
automatically created with the type of the rvalue if needed.

If I try to read a variable that doesn’t exist, I’ll get an exception.

But what if I try to set the wrong variable name? e.g.:

number = 3
numbr += 1 # a typo
puts number # prints 3, but should have printed 4

Is there a way to protect myself from typos on lvalue variable names?


Quantum Mechanics: The dreams stuff is made of


(Chris Morris) #3

number = 3
numbr += 1 # a typo
puts number # prints 3, but should have printed 4

Is there a way to protect myself from typos on lvalue variable names?

Well, literally in that case, you’d get this error:

irb(main):001:0> numbr += 1
NameError: undefined method `+’ for nil
from (irb):1

Now, if numbr had been used previously, you’d still have your original
issue – there’s no declaring of variables (like VB’s Option Explicit) to
protect you.

One Best Practice that seems to cover nicely for this sort of thing is unit
testing. The benefits of unit testing go beyond preventing simple mistakes
like this one. It is sort of a non-answer to your question, but I’ve rarely
run into problems with the dynamic typing and declaration-free attributes of
Ruby with unit testing.

Chris