将示例 java 代码转换为 ruby 以理解 ruby 中的静态变量

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

谁能帮我把这个简单的 java 代码转换成 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;
 }
}

我正在尝试了解静态方法的基本内存缓存。如何在 Ruby.

上实现相同的功能

使用 @@ 分配一个 class 变量,该变量与 class 的所有实例共享:

class A
  @@cached_names = nil

  def self.get_names
    @@cached_names = prepare_names if !@@cached_names
    @@cached_names
  end
end

关键字self表示将方法指定为class方法(类似于Java中的静态方法)。如果没有 self 关键字,该方法将成为实例方法。

这是一个不错的 summary of class and instance methods: