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 开发者_StackOverflow中文版state the pros & cons.
@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
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?
精彩评论