简体   繁体   English

Ruby中的类变量实例变量

[英]Class variables instance variables in Ruby

I was trying to get a dynamic array for in RUBY which will be changed dynamically. 我试图在RUBY中获得一个动态数组,该数组将动态更改。 I could not able to push to class variable. 我无法推送到类变量。 Can any one help how can i do that please see the below code. 任何人都可以帮忙吗,请查看下面的代码。

class SampleController < ApplicationController

  @@array = []
  @@x = 0

  def ajax_data    
    y = (rand()*100).round()
    @@array << [@@x,y]
    @@x += 1   
  end 

end

My Question is that the class variable @@array should increase the size of the array whenever we call to the method ajax_data but it always gives the output of one value like this [ [0, y] ] . 我的问题是,每当我们调用方法ajax_data时,类变量@@array都应该增加@@array的大小,但是它总是提供一个像[ [0, y] ]这样的值的输出。 I want to increase the @@array and @@x values . 我想增加@@array and @@x值。

How can we do that ? 我们该怎么做?

Ruby on Rails, in development mode, by default reloads your source files on each request. 在开发模式下,Ruby on Rails默认情况下会在每次请求时重新加载您的源文件。 Since you're saving your "program"'s state in class variables, the changes get wiped out by the reloading of your classes. 由于将“程序”的状态保存在类变量中,因此更改将通过重新加载类而消失。

By the way, class variables are normally used with much caution, as they are essentially global. 顺便说一句,由于类变量本质上是全局变量,因此通常要格外谨慎。 Especially in a Rails web application. 特别是在Rails Web应用程序中。 Save any state in a database, not in your classes' context. 将任何状态保存在数据库中,而不是在类的上下文中。

Update: 更新:

Remember that web server processes are usually supposed to be stateless. 请记住,Web服务器进程通常应该是无状态的。 Also, you usually have multiple processes running in production, which means that your counter would be different between requests depending on which process would answer a request. 另外,生产中通常会运行多个进程,这意味着请求之间的计数器会有所不同,具体取决于哪个进程会响应请求。 Also, processes can be restarted, meaning you counter would be lost. 此外,可以重新启动进程,这意味着您的计数器将丢失。

In Rails, if something is this tricky, it usually means you're trying to do something that you shouldn't do :) 在Rails中,如果有些棘手的事情,通常意味着您正在尝试做一些不应该做的事情:)

If you really don't want to use a DB, and if the counter is not supposed to be global for all visitors of your page, you could try storing the counter in a cookie: http://api.rubyonrails.org/classes/ActionDispatch/Cookies.html 如果您确实不想使用数据库,并且该计数器对于页面的所有访问者都不应该是全局的,则可以尝试将计数器存储在cookie中: http : //api.rubyonrails.org/classes /ActionDispatch/Cookies.html

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

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