Static variables in Ruby

Hi –

On Wed, 25 Jul 2007, Robert D. wrote:

Interesting. That is because Float, Regexp, and Bignum are instantiated
def foo(x)
(0…0).instance_eval{x,@x = @x,x}
x
end

3.times{ |i| puts foo(i) }
(0…0).instance_eval{@x=42}
3.times{ |i| puts foo(i) }

Run this for a pleasant surprise :slight_smile:

I get the same result with or without the line between the two times
calls. Are you seeing it output 42?

David

On 7/25/07, Robert K. [email protected] wrote:

functions (like in C/C++)

But it seems to be true :wink:

=> 5
Actually this is a reason why it should not work
def f; (0…0).object_id end
2.times{ p f }
p (0…0).object_id
Nevertheless it does because of the scope local optimization if I
understood Joël correctly.
69626560
=> 5

Kind regards

robert

Hmm as we are exploring it, let us see if it works for all constants,
somehow I doubt it…
Fixnum ranges work, Bignum ranges do not
646/146 > cat rang_oid.rb && ruby rang_oid.rb
#!/usr/local/bin/ruby

vim: sw=2 sts=2 ft=ruby expandtab tw=0:

def f; “08%x” % (1…1073741823).object_id end
def b; “08%x” % (1…1073741824).object_id end

puts “f”
3.times{ puts f }
puts “b”
3.times{ puts b }
f
08…fdbeb46ae
08…fdbeb46ae
08…fdbeb46ae
b
08…fdbeb4366
08…fdbeb4334
08…fdbeb4302

So for bignums the values will not be kept.

Robert

On 7/25/07, [email protected] [email protected] wrote:

Is any way to define static variables over function? As class static
The literal object can be Float, Regexp or Bignum, but Range

3.times{ |i| puts foo(i) }

Run this for a pleasant surprise :slight_smile:

I get the same result with or without the line between the two times
calls. Are you seeing it output 42?
No that is the pleasant surprise :slight_smile:
If I understood the Guru Sans correctly that is because the
interpreter defines (0…0) scope locally – the same object_id
notwithstanding – amazing feature indeed.
Needless to say that one should rather not use it :wink:

Cheers
Robert