开发者

How do you initialize variables in Ruby?

开发者 https://www.devze.com 2023-01-14 18:47 出处:网络
Are there any differences between the following ways of initialization of variables? @var ||= [] @var = [] if @var.nil?

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?

0

精彩评论

暂无评论...
验证码 换一张
取 消