@var in Ruby is an instance variable, which can be accessed in all methods of the class; for variables that do not contain @, their scope is within the current method.
ROR is to render the template by calling another method after the current method is executed. In this way, the most convenient way to pass variables between two methods is to use instance variables. If you use ordinary variables and exceed the scope, an error will naturally be reported.
Variables starting with @ are instance variables in Ruby. In contrast, variables starting with @@ are class variables.
In Rails, data is passed between controllers and views through instance variables. This procedure is default and does not need to be passed explicitly.
Use variables starting with @ as instance variables.
In your scenario, when you initiate an http request, the rails routing mechanism matches the index method of MyController for response.
So the following things will happen:
1. Initialize a MyController instance and execute the index method.
2. Set the instance variable @output of the controller to '123'.
3. Since you did not specify any render specifically, index.html.erb will be rendered by default
4. Copy all instance variables of the controller (removing some that should not be copied)
5. Instantiate a view and set the instance variables just copied from the controller to the view.
6. In this way, you can get this instance variable in the view.
@var in Ruby is an instance variable, which can be accessed in all methods of the class; for variables that do not contain @, their scope is within the current method.
ROR is to render the template by calling another method after the current method is executed. In this way, the most convenient way to pass variables between two methods is to use instance variables. If you use ordinary variables and exceed the scope, an error will naturally be reported.
Variables starting with @ are instance variables in Ruby. In contrast, variables starting with @@ are class variables.
In Rails, data is passed between controllers and views through instance variables. This procedure is default and does not need to be passed explicitly.
Just remember this rule.
@ in Ruby is equivalent to self in Python
Use variables starting with
@
as instance variables.In your scenario, when you initiate an http request, the rails routing mechanism matches the index method of MyController for response.
So the following things will happen:
1. Initialize a MyController instance and execute the index method.
2. Set the instance variable @output of the controller to '123'.
3. Since you did not specify any render specifically, index.html.erb will be rendered by default
4. Copy all instance variables of the controller (removing some that should not be copied)
5. Instantiate a view and set the instance variables just copied from the controller to the view.
6. In this way, you can get this instance variable in the view.