简体   繁体   中英

Why doesn't Ruby confuse two instance variables in different methods in the same class?

class Order < ApplicationController

  def new
    @project = Project.new
  end

  def show
    @project = Project.find(params[:id])
  end
end

So why doesn't Ruby/Rails get confused with the same instance variables in two different methods within the same class?

As a Rails controller, it is invoked when /new or /show is requested by the browser. For each request a new instance of the controller class is created. So either new or show will be executed, but not both.

Because a new instance of the class is created to handle every request.

[EDIT]: if you were to have another method called Order#do_stuff_with_project , you could call it from both Order#show and Order#new , and it could access the @project variable. They are simple methods, nothing magical.

Or you can put it this way: by convention both methods are never called on the same controller instance. It's an example of temporal coupling .

每当刷新页面时,都会再次向该控制器发送一个请求,该请求将被初始化。

Instance methods are only called in an instance of an object

An instance of an object is when it is loaded / called / initialized, meaning that the instance variable can only be used when that particular object is loaded

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM