1

I just want to have an array as global, so when I add or remove an element, it can be reflected anywhere in the class.

For example:

class something
  @@my_array = Array.new
  def self.action_1
    @@my_array << 1
    @@my_array << 2
    @@my_array << 3
  end

   def self.how_many_elements
     puts "# of elements: " + @@my_array.size.to_s
   end
end

If i do the following:

something.action_1 => from controller_a

something.how_many_elements => from controller b

I always get the following output:

"# of elements: 0"

Why?

1
  • Quite aside from the fact that @@class variables won't do what you want here, it's never a good idea to use @@class variables in Ruby. Forget that they exist; use class @instance variables instead -- they function similarly but with fewer surprises. Commented Nov 29, 2011 at 17:46

2 Answers 2

5

It's a common mistake to think that you can stash things in your classes and they will persist between requests. If this happens it is purely coincidence and it is a behavior you cannot depend on.

Using global variables in this fashion is almost a bad idea. A properly structured Rails application should persist data in the session, the database, or the Rails.cache subsystem.

Each request serviced by Rails in development mode will start with a virtually clean slate, where all models, controllers, views and routes are reloaded from scratch each time. If you put things in a class thinking it will be there for you the next time around, you're going to be in for a surprise.

For saving things that are not important, use the Rails cache or the session facility. For saving things that are important, use a database.

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

Comments

1

Use class variables:

class something

  @@my_array = []

  def self.action_1
    @@my_array << 1
    @@my_array << 2
    @@my_array << 3
  end

   def self.how_many_elements
     puts "# of elements: " + @@my_array.size
   end
end

1 Comment

Either would work under normal circumstances, although class variables would be preferable. Turns out it's unrelated to the type, though.

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.