问题
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