13

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.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
PeterWong
  • 15,951
  • 9
  • 59
  • 68

2 Answers2

5

@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

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
fantactuka
  • 3,298
  • 19
  • 29
5

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?

Community
  • 1
  • 1
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
  • 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 Sep 07 '10 at 01:42
  • 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 Sep 07 '10 at 02:42