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
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.