def index
@hash ||= Hash.new
puts @hash #the result is {} every time I reload the action
@hash['key'] = value
end
I thought by doing this the variable @hash will be signed just once.
But turns out, if I am right, the @hash will be a new empty hash every time I reload the index action.
Am I right or there is another reason for this odd phenomenon?
Tokland gave you the right suggestion of using
sessionobject, and I can only serve you with a little more detailed explanation.The operator
||=works as you expect, but you assumed that the same object handles all your requests. In Rails a new instance of the controller is created for handling every request. The class is cached (at least in production and test environment), but the instances are not.This way of handling requests ensures that your action does not need to worry about instance variables from other actions, and even from previous calls of the same action. Thus you may be sure that if your action did not set a variable, then it is nil.
If you are curious, you can test how this would behave if you define a class-method and handle the instance variable there. (Just remember that in
developmentthe class is also recreated for each request)