Is there any way to require that all variables and class attributes be
predeclared? I’m looking for something similar to Perl’s strict
pragma. It would prevent bugs like this:
class Demo
def initialize
@count = 0
end
def anotherfunc
@cout += 1
end
def get_count
@count
end
end
d = Demo.new
puts d.get_count
d.anotherfunc
d.get_count
Note the typo in anotherfunc. This code was intended to output a zero
followed by a one, but because of the typo, will output two 0’s.
Is there any way to prevent errors like this from happening?
method one - use ruby’s ability to declare accessors
~ > cat a.rb
class Demo
attr :count, 1
def initialize
self.count = 0
end
def anotherfunc
self.cout += 1
end
def get_count
self.count
end
end
d = Demo.new
puts d.get_count
d.anotherfunc
d.get_count
~ > ruby a.rb
0
a.rb:7:in anotherfunc': undefined method
cout’ for #<Demo:0x400a3cc8 @count=0> (NoMethodError)
from a.rb:16
method two - turn on warnings
~ > cat b.rb
$VERBOSE = true
class Demo
def initialize
@count = 0
end
def anotherfunc
@cout += 1
end
def get_count
@count
end
end
d = Demo.new
puts d.get_count
d.anotherfunc
d.get_count
~ > ruby b.rb
0
b.rb:8: warning: instance variable @cout not initialized
b.rb:8:in anotherfunc': undefined method
+’ for nil:NilClass (NoMethodError)
from b.rb:17
I find it hard to believe that a language as well-designed as Ruby would
lack this simple feature.
it’s the ‘-w’ switch ($VERBOSE = true)
-a
···
On 9 Mar 2004, Bill Atkins wrote:
===============================================================================
EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov
PHONE :: 303.497.6469
ADDRESS :: E/GC2 325 Broadway, Boulder, CO 80305-3328
URL :: Solar-Terrestrial Physics Data | NCEI
TRY :: for l in ruby perl;do $l -e “print "\x3a\x2d\x29\x0a"”;done
===============================================================================