ruby中的静态变量,如C函数中的静态变量

ruby中的静态变量,如C函数中的静态变量,ruby,Ruby,Ruby中有没有像静态变量这样的东西会像在C函数中那样运行 这里有一个简单的例子来说明我的意思。它将“6\n7\n”打印到控制台 #include <stdio.h> int test() { static int a = 5; a++; return a; } int main() { printf("%d\n", test()); printf("%d\n", test());

Ruby中有没有像静态变量这样的东西会像在C函数中那样运行

这里有一个简单的例子来说明我的意思。它将“6\n7\n”打印到控制台

#include <stdio.h>

int test() {
        static int a = 5;
        a++;
        return a;
}

int main() {

        printf("%d\n", test());
        printf("%d\n", test());

        return 0;
}
#包括
int测试(){
静态int a=5;
a++;
返回a;
}
int main(){
printf(“%d\n”,test());
printf(“%d\n”,test());
返回0;
}

您可以使用全局变量:

$a = 5
def test
  $a += 1
end

p test #=> 6
p test #=> 7

Ruby中没有与C的
静态
变量等价的语法,我在类似抽象级别的语言中从未见过类似的东西,比如Javascript、Python、Elixir等等

我对这段C代码的理解是,第一次调用函数时,编译器用初始值初始化变量。后续调用将只获取变量的当前值

这就是我用ruby术语翻译相同逻辑的方式:

def test()
  @a ||= 5 # If not set, set it. We need to use an instance variable to persist the variable across calls.
  @a += 1 # sum 1 and return it's value
end

def main()
  puts test
  puts test
  0
end

这在课堂之外也有效。

类似于尼科加的答案,但更独立:

def some_method
  @var ||= 0
  @var += 1
  puts @var
end

在方法中确定变量的作用域并返回lambda

def counter
  count = 0
  lambda{count = count+1}
end

test = counter
test[]
#=>1
test[]
#=>2

我认为这样做的标准方法是使用
光纤

f = Fiber.new do
  a = 5
  loop{Fiber.yield a += 1}
end

puts f.resume # => 6
puts f.resume # => 7
...

在singleton类(静态类本身)中使用变量

在ruby中,任何类都是只有一个实例的对象。 因此,您可以在类上创建实例变量,它将作为“静态”方法工作;)

输出:

  ruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-linux]

=> :counter
   Single.counter
=> 5
   Single.counter
=> 6
   Single.counter
=> 7
要在主作用域上获得此行为,可以执行以下操作:

module Countable
  def counter
    if @count  
      @count+=1
    else
      @count = 5
    end
  end
end

=> :counter
   self.class.prepend Countable # this "adds" the method to the main object
=> Object
   counter
=> 5
   counter
=> 6
   counter
=> 7

我接受这一点,因为它似乎最接近我的要求。谢谢@戴维杜里克闭包?C语言和C++中,静态变量是在应用程序首次启动时创建和初始化的,而不是在第一次运行包含它们的函数时初始化的。
module Countable
  def counter
    if @count  
      @count+=1
    else
      @count = 5
    end
  end
end

=> :counter
   self.class.prepend Countable # this "adds" the method to the main object
=> Object
   counter
=> 5
   counter
=> 6
   counter
=> 7