C's static equivalent

More or less:

def make_closure
perm_variable = 0
return proc {
perm_variable += 1
puts "I have been called “, perm_variable, " times.”
}
end

def use_closure
fun = make_closure
fun.call
fun.call
fun.call
end

use_closure

Should print out

I have been called 1 times.
I have been called 2 times.
I have been called 3 times.

However, each time you call make_closure, it returns a separate context, so:

def use_closure2
fun1 = make_closure
fun2 = make_closure

fun1.call
fun2.call
fun1.call
end

use_closure2

Should print:

I have been called 1 times.
I have been called 1 times.
I have been called 2 times.

Because fun1 and fun2 store two separate states of perm_variable.
At least that’s my understanding of closures.

As far as I know, there’s nothing quite like C’s static
in Ruby, since there’s no way to make a variable local
in scope to a function, but persistant in state over all
calls to that function (at least that I know of).

  • Dan
···

----- Original Message -----
From: KONTRA Gergely kgergely@mlabdial.hit.bme.hu
Date: Thursday, August 7, 2003 9:59 am
Subject: Re: C’s static equivalent

On 0807, ts wrote:

Is there something similar to C’s static keyword?
I want a single function, which has to access and modify a
variable. Any solution without bundling the function
to a class?
Use a closure
Could you be more verbose? Eg. how to print out how many times a
function was called.

Gergo

±[ Kontra, Gergelykgergely@mcl.hu PhD student Room IB113 ]------
—+

http://www.mcl.hu/~kgergely “Olyan langesz vagyok,
hogy |
Mobil:(+36 20) 356 9656 ICQ: 175564914 poroltoval kellene
jarnom” |
±- Magyar php mirror es magyar php dokumentacio:
http://hu.php.net --+

A C ‘static’ variable is just a global variable with a lexically local
scope, so a class variable (@@count += 1) is probably the closest
equivalent. The scope extends to the whole object though, not just the
method.

Regards,

Brian.

···

On Thu, Aug 07, 2003 at 11:18:17PM +0900, djd15@cwru.edu wrote:

As far as I know, there’s nothing quite like C’s static
in Ruby, since there’s no way to make a variable local
in scope to a function, but persistant in state over all
calls to that function (at least that I know of).