I hope for an explanation why the example code behaves the way it does. The example is taken from a Rails project, where the Example
class has a database field called settings
with type text
.
As far as I know Ruby, calling settings
, same as self.settings
, would read the database field (as there is no local settings
variable), while settings = ...
would create a local variable and self.settings = ...
would set a value in the database. With this knowledge, I can't explain the behavior I encountered and am trying to show in this example. I hope the inline comments are sufficient to explain the cases.
class Example
# db field: t.text "settings", with current value "" (empty string)
def example
details = {status: "something"}
self.settings = settings.merge(details) # => {:status=>"something"}
settings # => {:status=>"something"}
# ok so far
settings = settings.merge(details) # => NoMethodError: undefined method `merge' for nil:NilClass
# why would `settings` after the equal sign suddenly be nil? It wasn't above.
end
def example2
details = {status: "something"}
# running this not valid line on purpose
settings = settings.merge(details) # => NoMethodError: undefined method `merge' for nil:NilClass
self.settings = settings.merge(details) # => NoMethodError: undefined method `merge' for nil:NilClass
# after running the second (merge) line, the valid third (merge) line (was valid in the first `example` method) suddenly throws an error, unlike the first time.
# why isn't it valid anymore?
end
end