Just curious if there is a more elegant way to set a variable if it happens to not exist yet. I often find I am doing somthing like the following:
regex = ''
10.times { regex += '.*,.*,.*,.*,.*,.*,.*,.*,.*,.*,.*,.*,.*,.*\n' }
Is there some prettier way to within the second line create the variable if it does not exist yet? The above just looks ugly. I know I could use a class variable but that also does not seem right as I do not need it to be a class variable:
10.times { @regex += '.*,.*,.*,.*,.*,.*,.*,.*,.*,.*,.*,.*,.*,.*\n' }
Having no idea what the context is I’ll try to answer:
Since the code where you’re modifying your variable is w/in a block, any variables referenced therein that don’t already exist (outside the block) won’t exist outside the block once after it has run:
$ cat test.rb
1.times { hi = “hello” }
defined?(hi) ? hi += " bye" : hi = “NOT DEFINED”
puts hi
$ ruby test.rb
NOT DEFINED
Thus, for your block to have any effect on local variables that exist in the enclosing scope these variables must already “exist” before the block. This means the parser must see the local variable (in some context where it is clear it is a local variable and not a method call, such as in an assignment statement) before the block definition in the enclosing scope.
So, assuming I understand your intent, the answer is no. The local must already be defined (whether initialized with an actual value is another matter (*see example below)) or you should use an instance, class, or global.
$ cat test.rb
hi = nil if false # defines hi even though assignment never executed
1.times { hi = “hello” }
defined?(hi) ? hi += " bye" : hi = “NOT DEFINED”
puts hi
$ ruby test.rb
hello bye
I don’t know if this helps any or not…