views:

95

answers:

2

Are there any differences between the following ways of initialization of variables?

@var ||= []
@var = [] if @var.nil?
@var = @var || []

Please share your way initializing a variable and state the pros & cons.

+2  A: 

@var ||= [] and @var = @var || [] are equal it will set var to [] if it's false or nil

@var = [] if @var.nil? is more specific - will re-set var to [] only if it's equal to nil

fantactuka
So will rails automatically checks `@var` is null in the `||` case? or will `.nil?` a small small overhead?
PeterWong
Yes, all these examples checks for `nil`. 1st and 3rd also checks for `false`
fantactuka
+2  A: 

If you have warnings on (and you should!), @var ||= [] behaves differently to @var = @var || []:

irb(main):001:0> $VERBOSE = true
=> true
irb(main):002:0> @var ||= []
=> []
irb(main):003:0> @var2 = @var2 || []
(irb):3: warning: instance variable @var2 not initialized
=> []
irb(main):004:0>

If you wish to check whether @var is defined or not, and you're happy if it's nil or false, you can use

@var = [] unless defined?(@var)

This won't work with local variables though, as noted in In Ruby why won't foo = true unless defined?(foo) make the assignment?

Andrew Grimm
Thanks! I didn't noticed the warning message before. BTW, how to show the warning messages in the console? Mine didn't show it.
PeterWong
If you're using version 1.9.2, `irb -w` or `irb -d` will turn on the warnings (I don't know whether the similar `irb -v` will work). For earlier versions, you have to set `$VERBOSE` yourself. (`irb -d` working was the result of [my bugfix](http://redmine.ruby-lang.org/issues/show/3634) that resulted from another person's SO question)
Andrew Grimm