Search code examples
javarubycachingstatic-methodsclass-method

Convert sample java code to ruby to understand static variales in ruby


can anybody help me to convert this simple java code to ruby.

class A {
 private static String[] chachedNames;

 public static String[] getNames(){
  if(chachedNames == null)
   chachedNames = prepareNames(); //This process will take 20sec to complete
  return chachedNames;
 }
}

I'm trying to understand basic memory caching on static method. How do implement same on Ruby.


Solution

  • Use @@ to assign a class variable that is shared with all instances of that class:

    class A
      @@cached_names = nil
    
      def self.get_names
        @@cached_names = prepare_names if !@@cached_names
        @@cached_names
      end
    end
    

    The keyword self means assign the method to be a class method (analogous to a static method in Java). Without the self keyword, the method becomes an instance method.

    Here's a nice summary of class and instance methods: