Checking if a variable is defined?

2019-01-04 15:23发布

How can I check whether a variable is defined in Ruby? Is there an isset-type method available?

14条回答
▲ chillily
2楼-- · 2019-01-04 16:22

Also, you can check if it's defined while in a string via interpolation, if you code:

puts "Is array1 defined and what type is it? #{defined?(@array1)}"

The system will tell you the type if it is defined. If it is not defined it will just return a warning saying the variable is not initialized.

Hope this helps! :)

查看更多
唯我独甜
3楼-- · 2019-01-04 16:24

This is the key answer: the defined? method. The accepted answer above illustrates this perfectly.

But there is a shark, lurking beneath the waves...

Consider this type of common ruby pattern:

 def method1
    @x ||= method2
 end

 def method2
    nil
 end

method2 always returns nil. The first time you call method1, the @x variable is not set - therefore method2 will be run. and method2 will set @x to nil. That is fine, and all well and good. But what happens the second time you call method1?

Remember @x has already been set to nil. But method2 will still be run again? If method2 is a costly undertaking this might not be something that you want.

Let the defined? method come to the rescue - with this solution, that handles that particular case.

  def method1
    return @x if defined? @x
    @x = method2
  end

The devil is in the details: but you can evade that lurking shark by just getting "a bigger boat".

查看更多
登录 后发表回答