简体   繁体   English

为什么Ruby不会在同一个类的不同方法中混淆两个实例变量?

[英]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? 那么,为什么在同一个类中的两个不同方法中,Ruby / Rails不会与相同的实例变量混淆?

As a Rails controller, it is invoked when /new or /show is requested by the browser. 作为Rails控制器,当浏览器请求/new/show时将调用它。 For each request a new instance of the controller class is created. 对于每个请求,将创建控制器类的新实例。 So either new or show will be executed, but not both. 因此,将执行newshow ,但不会两者都执行。

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. [编辑]:如果要使用另一个名为Order#do_stuff_with_project方法,则可以从Order#showOrder#new调用它,并且可以访问@project变量。 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 对象的实例是在加载/调用/初始化时表示的,这意味着只能在加载特定对象时使用实例变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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