0

I was trying to get a dynamic array for in RUBY which will be changed dynamically. 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] ] . I want to increase the @@array and @@x values .

How can we do that ?

1
  • I've used your code and gets the right values of @@array pastie.org/3372267 Commented Feb 13, 2012 at 8:01

1 Answer 1

3

Ruby on Rails, in development mode, by default reloads your source files on each request. 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. Save any state in a database, not in your classes' context.

Update:

Remember that web server processes are usually supposed to be stateless. 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 :)

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply palmer. Is there any way to do this functionality like increasing @@array when ever the request comes to that method in ruby. I don't want to store in database
Thanks Palmer. Will try that and let you know

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.