Ruby: why does an undeclared instance variable return nil

天涯浪子 提交于 2021-01-29 04:00:58

问题


Given the following class:

class Something
  def initialize
    @test = "test"
  end
end

Why does ruby return nil when invoking an undeclared instance variable?

thingy = Something.new
thingy.instance_variable_get(:@var)  # nil
thingy.instance_variable_get(:@test) # "test"

As opposed to some error message indicating the variable is missing from the instance. The answer I am hoping for is an explanation as to the reasoning behind ruby's implementation of instance variables in this way.


回答1:


It's just the way instance variables implemented in Ruby. Same for global variables. Also you can see warnings for such things if you pass -w parameter to ruby.

✗ irb -w
2.3.1 :001 > @a
(irb):1: warning: instance variable @a not initialized
=> nil 



回答2:


Because, instead of throwing an error, objects are allowed to have empty values. Such as a user, must have a name and address but email address is optional, a check can be done for nil before continuing.

if customer1.name == nil #personalized error code here
if customer1.email == nil customer1.email = "not given"


来源:https://stackoverflow.com/questions/37753581/ruby-why-does-an-undeclared-instance-variable-return-nil

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!