Static variables in ruby, like in C functions

前端 未结 6 1642
花落未央
花落未央 2021-01-22 08:29

Is there any such thing as static variables in Ruby that would behave like they do in C functions?

Here\'s a quick example of what I mean. It prints \"6\\n7\\n\" to the

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-22 09:02

    There is no syntactical equivalent to C's static variables in Ruby, and I've never seen something like that in languages with similar level of abstraction, like Javascript, Python, Elixir, etc.

    What I understand about this C code is that the first time the function is called the compiler initializes the variable with the initial value. Subsequent calls will just get the current value of the varible.

    This is how I would translate the same logic in ruby terms:

    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
    

    This works outside a class too.

提交回复
热议问题