On Wed, Dec 15, 2010 at 9:07 AM, femto Zheng <femtowin / gmail.com> wrote: > Hello all, > in ruby c source code, there is > <http://codesearch.google.com/codesearch/p?hl=en#kOEgDIzD-Ao/trunk/lib/ruby/re.c&q=define_virtual&sa=N&cd=1&ct=rc&l=3369>rb_define_virtual_variable > like > rb_*define_virtual*_variable("$~", match_getter, > match_setter);<http://codesearch.google.com/codesearch/p?hl=en#kOEgDIzD-Ao/trunk/lib/ruby/re.c&q=define_virtual&sa=N&cd=1&ct=rc&l=3369> ... > so actually this looks like global variable, but when you get/set it, > it will run thru a function, They are not global variables, they are more restricted: these variables are local to the current stack frame, which also makes them thread local at the same time. You can see it here: irb(main):001:0> def a irb(main):002:1> /x+/ =~ "xxxxxyyyyy" irb(main):003:1> p $& irb(main):004:1> b irb(main):005:1> end => nil irb(main):006:0> def b irb(main):007:1> p $& irb(main):008:1> end => nil irb(main):009:0> a "xxxxx" nil => nil irb(main):010:0> > How do I do it in Ruby code? make a global variable running through my > customized get/set procedure? What do you want to achieve? Why do you think you need this? You can always do class X def foo=(val) printf "Setting foo to %p\n", val end def foo puts "Getting foo" 123 end end irb(main):011:0> $GlobalX = X.new => #<X:0x1003cd44> irb(main):012:0> $GlobalX.foo = "hello" Setting foo to "hello" => "hello" Apart from that global state is always dangerous and should be avoided if possible. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/