From: lalawawa Date: 2010-06-10T07:35:09+09:00 Subject: Re: newbie question Hi Robert, I assume that if I use the value of an unassigned variable ruby will catch me. What I am worried about is if I misspell a variable name while assigning to it. myLongName = 'woof' if haveACat myLoongName += ' and meow' end puts myLongName I misspelled 'myLongName' the second time, so it's like the assinment didn't happen. If I had been in perl and said 'my myLongName' and 'use strict', it would have caught the first time I ran it, even if I didn't test the case where 'haveACat' is true. Robert Klemme wrote: > 2010/6/9 lalawawa : >> In perl, one is able to sort of 'declare' variables by mentioning them >> in 'my' statements. Then, if you say 'use strict;', no variables that >> weren't previously thus 'declared' are allowed. This is useful in that >> it catches typos that might be difficult to detect in testing. >> >> Does ruby have an equivalent mechanism? > > Better: you do not need an additional declaration, rather Ruby will > catch situations for you where you forgot to initialize (aka assign) a > local variable: > > $ ruby19 -e 'puts foo' > -e:1:in `
': undefined local variable or method `foo' for > main:Object (NameError) > > The grain of salt is this > > - this does not work for instance variables, these spring into > existence whenever you use them, > > - because there is the method local variable ambiguity you might still > run into erroneous situations when forgetting to initialize a local > variable which shares name with a method. > > Kind regards > > robert >