From: Nicholas Van Weerdenburg Date: 2004-07-14T12:34:24+09:00 Subject: Re: instance variable question in test/unit TestCase @myvar ||= 1 # initialize @myvar, but only if it's nil @myvar = 1 unless defined?(@myvar) Ah, the first idiom is neat. I hadn't seen that one. Unfortunately, the issue I still have is that I don't have a single place where I want to set these- the variable is in many methods. Hmmm...Java code generator in Ruby. I like it! Thanks, Nick Joel VanderWerf wrote: > Nicholas Van Weerdenburg wrote: > >> 1. A more general question: how do I initialize instance variables >> without an "initialize" method? In my test case, I want instance >> variables, but placing "@myvar=1" outside a method doesn't seem to >> work ( I dimly recall that this is a class instance variable or >> something like that). The reason I want to do this is that in >> subclassing Test::Unit::TestCase I don't know offhand what it's >> initialize method looks like (a no arg "initialize" gives an argment >> number error) and don't want to learn just for this reason. >> >> I just thought of trying the following- >> >> def initialize *args >> super *args >> @myvar=1 >> end >> >> and it worked (I think). Cool. >> >> My other option is the setup method, since that is called for before >> all test methods. Are there any other options? > > > Use the ||= idiom. I like it because it can keep the initialization > near the point of use. > > def foo > @myvar ||= 1 # initialize @myvar, but only if it's nil > end > > Of course, this assumes that nil is not an expected value for the > variable. Otherwise, you can use > > @myvar = 1 unless defined?(@myvar) > >> 2. where do I find the will to return to programming in Java now that >> I'm having so much fun in Ruby? > > > Dunno.. write a java code generator in ruby? >